如何删除非空目录?
我正在尝试使用 rmdir
删除一个目录,但我收到了目录非空"消息,因为其中仍有文件.
I am trying to remove a directory with rmdir
, but I received the 'Directory not empty' message, because it still has files in it.
我可以使用什么函数来删除包含所有文件的目录?
What function can I use to remove a directory with all the files in it as well?
推荐答案
没有内置函数可以做到这一点,但请参阅 http://us3.php.net/rmdir.许多评论者发布了他们自己的递归目录删除功能.您可以从中挑选.
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.
这是一个看起来不错的:
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);
}
如果您想保持简单,您可以只调用 rm -rf
.这确实使您的脚本仅适用于 UNIX,因此请注意这一点.如果你走那条路,我会尝试这样的事情:
You could just invoke rm -rf
if 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:
function deleteDirectory($dir) {
system('rm -rf -- ' . escapeshellarg($dir), $retval);
return $retval == 0; // UNIX commands return zero on success
}
相关文章