Home >Backend Development >PHP Tutorial >Summary of several methods to delete directories under PHP_PHP Tutorial
Haha, suddenly a friend asked me how to delete a directory, for example, if there are files below, I said to use deletion, but he said it was too slow. So I summarized the following methods.
1. Submission method: //I provided it, but it seems a little wrong, I haven’t tested it
deleteDir($dir)
{
if (rmdir($dir)==false && is_dir($dir)) {
if ($dp = opendir($dir)) {
while (($file=readdir($dp)) != false) {
if (is_dir($file) && $file! ='.' && $file!='..') {
deleteDir($file);
} else {
unlink($file);
}
}
closedir($dp);
} else {
exit('Not permission');
}
}
}
2. System call method // Senior brother provides
function del_dir($dir)
{
if(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$str = "rmdir /s/q " . $dir;
} else {
$str = "rm -Rf " . $dir;
}
}
3. Loop method //from: http://www.knowsky.com/1148.html
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!='..'))
Subordinate directory name
//if yes Just delete
}
}
function is_empty_dir($pathdir)
{
//Determine whether the directory is empty, isn’t my method very good? Just see if there are other things besides . and .. that are not empty
$d=opendir($pathdir);
$i=0;
while($a=readdir($d))
}
Haha, it’s enough for all kinds of friends, just decide according to your needs and speed.