【问题标题】:Deleting Directory Contents & SubDirectory Contents删除目录内容和子目录内容
【发布时间】:2012-10-19 01:43:42
【问题描述】:

我已经设置了一些 PHP 来删除一个目录,它的内容,以及任何子目录及其内容......我是 PHP 新手,所以我肯定做错了什么或者正在做一些效率最低的事情方式。

寻找一些关于如何更好地做到这一点的参考或建议......

顺便说一句,这段代码运行良好。使用 PHP 5.3.8。

chmod($main_dir, 0755);
if ($handle = opendir($main_dir)) {
    while (false !== ($entry = readdir($handle))) { 
        $absolute_path = $main_dir.'/'.$entry;
        if ($entry != "." && $entry != "..") {      
            chmod($absolute_path, 0755);
            unlink($absolute_path);

            //check if any folders exist, then delete files within
            if (file_exists($absolute_path) && is_dir($absolute_path)) {
                if ($child_handle = opendir($absolute_path)) {
                    while (false !== ($child_entry = readdir($child_handle))) {             
                    $child_absolute_path = $absolute_path.'/'.$child_entry;
                        if ($child_entry != "." && $child_entry != "..") {              
                            chmod($child_absolute_path, 0755);
                            unlink($child_absolute_path);
                        }
                    }
                    closedir($child_handle);
                }
            }
            rmdir($absolute_path);
        }
    }
    closedir($handle);
}
rmdir($main_dir);

有什么想法吗?非常感激! 我正在使用 PHP 5.3.8

【问题讨论】:

  • 这可能更适合code review
  • @shakabra 谢谢,现在去看看...

标签: php directory delete-file


【解决方案1】:

您可以使用RecursiveDirectoryIterator 列出所有文件和文件夹,然后将其删除。请注意,您必须使用RecursiveIteratorIterator::CHILD_FIRST,以便在文件夹之前删除文件。

$dir = __DIR__ . "/test";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
    $file->isDir() ?  rmdir($file) : unlink($file);
}

【讨论】:

  • 哇,简单多了...谢谢!一直在 php.net 上阅读,希望我很久以前就知道 RecursiveDirectoryIterator。
  • @Terry 学习是一件持续的事情......很高兴我能提供帮助
猜你喜欢
  • 2011-01-13
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
相关资源
最近更新 更多