使用 php 删除所有文件、文件夹及其子文件夹

2022-01-01 00:00:00 directory subdirectory file-io php

我需要一个脚本,它可以删除整个目录及其所有子文件夹、文件等.我尝试使用这个功能,几个月前我在互联网上找到了这个功能,但它不能完全工作.

I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely.

function deleteFile($dir) {
    if(substr($dir, strlen($dir)-1, 1) != '/') { 
        $dir .= '/'; 
    }
    if($handle = opendir($dir)) { 
        while($obj = readdir($handle)) { 
            if($obj != '.' && $obj != '..') { 
                if(is_dir($dir.$obj)) { 
                    if(!deleteFile($dir.$obj)) {
                        echo $dir.$obj."<br />";
                        return false;
                    }
                }
                elseif(is_file($dir.$obj)) { 
                    if(!unlink($dir.$obj)) {
                        echo $dir.$obj."<br />";
                        return false;
                    }
                }
            }
        }
        closedir($handle); 
        if(!@rmdir($dir)) {
            echo $dir.'<br />';
            return false;
        }
        return true;
    }
    return true;
}

为了测试,我使用了 prestashop 的解压存档,我尝试删除解压存档的文件夹,但它不起作用.

For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work.

/home/***/public_html/prestashop/img/p/3/
/home/***/public_html/prestashop/img/p/3
/home/***/public_html/prestashop/img/p
/home/***/public_html/prestashop/img

这些是问题文件夹.我第一次想 - 可能是文件的 chmod 有问题"但是当我测试所有文件的 chmod 权限 755(之后是 777) - 结果是一样的.

These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.

推荐答案

<?php
  function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           rrmdir($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }
?>

从 php.net

对我来说很好

相关文章