我想知道,删除一个包含所有文件的目录最简单的方法是什么?

我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。


当前回答

像这样的东西?

function delete_folder($folder) {
    $glob = glob($folder);
    foreach ($glob as $g) {
        if (!is_dir($g)) {
            unlink($g);
        } else {
            delete_folder("$g/*");
            rmdir($g);
        }
    }
}

其他回答

删除一个包含所有文件的目录最简单的方法是什么?

system("rm -rf ".escapeshellarg($dir));

现在至少有两种选择。

Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example: public static function deleteDir($dirPath) { if (! is_dir($dirPath)) { throw new InvalidArgumentException("$dirPath must be a directory"); } if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') { $dirPath .= '/'; } $files = glob($dirPath . '*', GLOB_MARK); foreach ($files as $file) { if (is_dir($file)) { self::deleteDir($file); } else { unlink($file); } } rmdir($dirPath); } And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself: $dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree'; $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) { if ($file->isDir()){ rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dir);

那么这个呢:

function recursiveDelete($dirPath, $deleteParent = true){
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
        $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
    }
    if($deleteParent) rmdir($dirPath);
}

我不敢相信有30多个答案。在PHP中递归删除一个文件夹可能需要几分钟,这取决于目录的深度和其中的文件数量!你可以用一行代码做到这一点…

Shell_exec ("rm -rf "。美元dir);

如果您关心删除整个文件系统,请首先确保您的$dir路径正是您想要的。永远不要允许用户输入一些可以直接删除文件的东西,而不首先严格验证输入。这是基本的编码实践。

平台独立代码。

我从PHP.net上得到了答案

if(PHP_OS === 'Windows')
{
 exec("rd /s /q {$path}");
}
else
{
 exec("rm -rf {$path}");
}