删除目录内容&子目录内容 [英] Deleting Directory Contents & SubDirectory Contents

查看:124
本文介绍了删除目录内容&子目录内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一些PHP来删除一个目录,它的内容,以及任何子目录及其内容...我是PHP的新手,所以我绝对会做错事或者做最不成功的事情

I've set up some PHP to delete a directory, it's contents, and any subdirectory and its contents... I'm new to PHP so I'm most definitely doing something WRONG or am doing something in the most inefficient way.

寻找一些参考或建议如何做到更好...

Looking for some references or suggestion on how to do this better...

顺便说一下,这段代码工作正常。使用PHP 5.3.8。

By the way, this code works fine. Using 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

Any thoughts? Much appreciated! Im using PHP 5.3.8

推荐答案

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

You can use RecursiveDirectoryIterator to list all files and folders then delete them. Please Note that you have to use RecursiveIteratorIterator::CHILD_FIRST so that the files are deleted before the folder.

$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);
}

这篇关于删除目录内容&子目录内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆