Home >Backend Development >PHP Tutorial >How to delete multi-level directories in php_PHP tutorial
Yesterday I saw a post (chinaasp) asking how to delete a directory. It has always been possible before, but yesterday something went wrong. It turned out that he just deleted the files at the lower level and then deleted the
directory. So if there are a few more levels, there will be question.
I can only make do with this temporarily. If your directory does not have more than ten levels, it should be fine~, but I am not familiar with recursion and can only do
deltree($ path);rmdir($path) to delete this directory. Is it possible to delete this directory directly with deltree($path);? ?
function deltree($pathdir)
{
echo $pathdir;//I use it when debugging
if(is_empty_dir($pathdir))//If it is empty
{
rmdir($pathdir);//Delete directly
}
else
{//Otherwise read this directory, except . and ..
$d=dir( $pathdir);
while($a=$d->read())
{
if(is_file($pathdir./.$a) && ($a!=.) && ($ a!=..)){unlink($pathdir./.$a);}
//If it is a file, delete it directly
if(is_dir($pathdir./.$a) && ($a !=.) && ($a!=..))
{//If it is a directory
if(!is_empty_dir($pathdir./.$a))//Is it empty
{/ / If not, call itself, which is just the original path + its subordinate directory name
deltree($pathdir./.$a);
}
if(is_empty_dir($pathdir./.$a ))
{//If it is empty, delete it directly
rmdir($pathdir./.$a);
}
}
}
$d->close() ;
echo "All files in the directory must be deleted first";//The
} I use when debugging