在 PHP 中,如何递归删除所有非空文件夹?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9760526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:34:58  来源:igfitidea点击:

In PHP how do I recursively remove all folders that aren't empty?

phpdirectoryrmdir

提问by Luká? Jeli?

Possible Duplicate:
How do I recursively delete a directory and its entire contents (files+sub dirs) in PHP?

可能的重复:
如何在 PHP 中递归删除目录及其全部内容(文件+子目录)?

I need to recursively delete a directory and subdirectories that aren't empty. I can't find any useful class or function to solve this problem.

我需要递归删除一个目录和非空的子目录。我找不到任何有用的类或函数来解决这个问题。

In advance thanks for your answers.

在此先感谢您的回答。

回答by lorenzo-s

From the first comment in the official documentation.

来自官方文档中的第一条评论。

http://php.net/manual/en/function.rmdir.php

http://php.net/manual/en/function.rmdir.php

<?php

 // When the directory is not empty:
 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);
   }
 }

?>

Edited rmdir to rrmdir to correct typo from obvious intent to create recursive function.

将 rmdir 编辑为 rrmdir 以纠正明显意图创建递归函数的拼写错误。

回答by alex

Something like this should do it...

这样的事情应该这样做......

function removeDir($path) {

    // Normalise $path.
    $path = rtrim($path, '/') . '/';

    // Remove all child files and directories.
    $items = glob($path . '*');

    foreach($items as $item) {
        is_dir($item) ? removeDir($item) : unlink($item);
    }

    // Remove directory.
    rmdir($path);
}

removeDir('/path/to/dir');

This deletes all child files and folders and then removes the top level folder passed to it.

这将删除所有子文件和文件夹,然后删除传递给它的顶级文件夹。

It could do with some error checking such as testing the path supplied is a directory and making sure each deletion was successful.

它可以进行一些错误检查,例如测试提供的路径是一个目录并确保每次删除都成功。

回答by d_inevitable

To recursively delete a directory use this:

要递归删除目录,请使用以下命令:

function rrmdir($path) {
    return is_file($path)? @unlink($path): array_map(__NAMESPACE__ . '\rrmdir',glob($path.'/*'))==@rmdir($path);
}

Only tested on unix.

仅在 unix 上测试。