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
}
这篇关于如何删除非空目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除非空目录?


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01