php 如何删除非空目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1653771/
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
How do I remove a directory that is not empty?
提问by zeckdude
I am trying to remove a directory with rmdir, but I received the 'Directory not empty' message, because it still has files in it.
我正在尝试删除带有 的目录rmdir,但我收到了“目录非空”消息,因为其中仍有文件。
What function can I use to remove a directory with all the files in it as well?
我可以使用什么功能来删除包含所有文件的目录?
回答by John Kugelman
There is no built-in function to do this, but see the comments at the bottom of http://us3.php.net/rmdir. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.
没有内置函数可以执行此操作,但请参阅http://us3.php.net/rmdir底部的注释。许多评论者发布了他们自己的递归目录删除功能。你可以从这些中挑选。
Here's one that looks decent:
这是一个看起来不错的:
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
You could just invoke rm -rfif you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:
rm -rf如果你想保持简单,你可以调用。这确实使您的脚本仅适用于 UNIX,因此请注意这一点。如果你走那条路,我会尝试这样的事情:
function deleteDirectory($dir) {
system('rm -rf -- ' . escapeshellarg($dir), $retval);
return $retval == 0; // UNIX commands return zero on success
}
回答by Abhay
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);
}
}
回答by AntonioCS
You could always try to use system commands.
您可以随时尝试使用系统命令。
If on linux use: rm -rf /dirIf on windows use: rd c:\dir /S /Q
如果在 linux 上使用:rm -rf /dir如果在 windows 上使用:rd c:\dir /S /Q
In the post above (John Kugelman) I suppose the PHP parser will optimize that scandir in the foreach but it just seems wrong to me to have the scandirin the foreachcondition statement.
You could also just do two array_shiftcommands to remove the .and ..instead of always checking in the loop.
在上面的帖子(John Kugelman)中,我认为 PHP 解析器将优化 foreach 中的 scandir,但在我看来scandir,在foreach条件语句中使用它似乎是错误的。
您也可以只执行两个array_shift命令来删除.and..而不是始终检查循环。
回答by Naman
Here what I used:
这是我使用的:
function emptyDir($dir) {
if (is_dir($dir)) {
$scn = scandir($dir);
foreach ($scn as $files) {
if ($files !== '.') {
if ($files !== '..') {
if (!is_dir($dir . '/' . $files)) {
unlink($dir . '/' . $files);
} else {
emptyDir($dir . '/' . $files);
rmdir($dir . '/' . $files);
}
}
}
}
}
}
$dir = 'link/to/your/dir';
emptyDir($dir);
rmdir($dir);
回答by Brandon Elliott
My case had quite a few tricky directories (names containing special characters, deep nesting, etc) and hidden files that produced "Directory not empty" errors with other suggested solutions. Since a Unix-only solution was unacceptable, I tested until I arrived at the following solution (which worked well in my case):
我的案例有很多棘手的目录(包含特殊字符、深层嵌套等的名称)和隐藏文件,这些文件与其他建议的解决方案产生“目录非空”错误。由于仅 Unix 的解决方案是不可接受的,因此我进行了测试,直到找到以下解决方案(在我的情况下效果很好):
function removeDirectory($path) {
// The preg_replace is necessary in order to traverse certain types of folder paths (such as /dir/[[dir2]]/dir3.abc#/)
// The {,.}* with GLOB_BRACE is necessary to pull all hidden files (have to remove or get "Directory not empty" errors)
$files = glob(preg_replace('/(\*|\?|\[)/', '[]', $path).'/{,.}*', GLOB_BRACE);
foreach ($files as $file) {
if ($file == $path.'/.' || $file == $path.'/..') { continue; } // skip special dir entries
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}
回答by Rain
Can't think of an easier and more efficient way to do that than this
想不出比这更简单、更有效的方法来做到这一点
<?php
$dirname = './myfolder';
if (is_dir($dirname)) {
$dir = new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST ) as $filename => $file) {
if (is_file($filename))
unlink($filename);
else
rmdir($filename);
}
rmdir($dirname); // Now remove myfolder
}
?>
回答by francoisV
I didn't arrive to delete a folder because PHP said me it was not empty. But it was. The function by Naman was the good solution to complete mine. So this is what I use :
我不是来删除文件夹的,因为 PHP 告诉我它不是空的。但它是。Naman 的功能是完成我的功能的很好的解决方案。所以这就是我使用的:
function emptyDir($dir) {
if (is_dir($dir)) {
$scn = scandir($dir);
foreach ($scn as $files) {
if ($files !== '.') {
if ($files !== '..') {
if (!is_dir($dir . '/' . $files)) {
unlink($dir . '/' . $files);
} else {
emptyDir($dir . '/' . $files);
rmdir($dir . '/' . $files);
}
}
}
}
}
}
function deleteDir($dir) {
foreach(glob($dir . '/' . '*') as $file) {
if(is_dir($file)){
deleteDir($file);
} else {
unlink($file);
}
}
emptyDir($dir);
rmdir($dir);
}
So, to delete a directory and recursively its content :
因此,要删除目录并递归其内容:
deleteDir($dir);
回答by Mykola Veriga
From http://php.net/manual/en/function.rmdir.php#91797
来自http://php.net/manual/en/function.rmdir.php#91797
Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.
Glob 函数不返回隐藏文件,因此当尝试递归删除树时, scandir 可能更有用。
<?php
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
?>
回答by kenorb
Try the following handy function:
试试以下方便的功能:
/**
* Removes directory and its contents
*
* @param string $path Path to the directory.
*/
function _delete_dir($path) {
if (!is_dir($path)) {
throw new InvalidArgumentException("$path must be a directory");
}
if (substr($path, strlen($path) - 1, 1) != DIRECTORY_SEPARATOR) {
$path .= DIRECTORY_SEPARATOR;
}
$files = glob($path . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
_delete_dir($file);
} else {
unlink($file);
}
}
rmdir($path);
}
回答by AbdulRahman AlShamiri
With this function, you will be able to delete any file or folder
使用此功能,您将能够删除任何文件或文件夹
function deleteDir($dirPath)
{
if (!is_dir($dirPath)) {
if (file_exists($dirPath) !== false) {
unlink($dirPath);
}
return;
}
if ($dirPath[strlen($dirPath) - 1] != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}

