How do I remove a directory that is not empty?(如何删除非空目录?)
问题描述
我正在尝试使用 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
}
这篇关于如何删除非空目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除非空目录?


基础教程推荐
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01