如何使用 PHP 删除包含内容的文件夹
我需要使用 PHP 删除包含内容的文件夹。 rmdir()
和 unlink()
删除空文件夹,但无法删除有内容的文件夹。
I need to delete a folder with contents using PHP. rmdir()
and unlink()
delete empty folders, but are not able to delete folders which have contents.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
此功能将允许您删除任何文件夹(只要它是可写的)及其文件和子目录。
或者不使用 RecursiveDirectoryIterator 进行递归:
This function will allow you to delete any folder (as long as it's writable) and it's files and subdirectories.
Or without recursion using
RecursiveDirectoryIterator
:您需要循环文件夹内容(包括任何子文件夹的内容)并首先删除它们。
这里有一个例子: http://lixlpixel.org/recursive_function/php/recursive_directory_delete/
小心一点!
You need to loop around the folder contents (including the contents of any subfolders) and remove them first.
There's an example here: http://lixlpixel.org/recursive_function/php/recursive_directory_delete/
Be careful with it!!!
你总是可以作弊并做
shell_exec("rm -rf /path/to/folder");
You could always cheat and do
shell_exec("rm -rf /path/to/folder");
PHP 中没有内置的单个函数可以实现此目的,您必须使用 rmdir 和 unlink 编写自己的函数。
一个示例(取自 php.net 文档 上的评论):
There is no single function build into PHP that would allow this, you have to write your own with rmdir and unlink.
An example (taken from a comment on php.net docs):
这是一个可以满足您需要的脚本:
我从 php.net 获取它并且它可以工作。
Here's a script that will do just what you need:
I got it from php.net and it works.
您必须递归删除所有文件。
rmdir
手册页的注释中有很多示例函数:http://www .php.net/rmdir
You will have to delete all the files recursively. There are plenty example functions in the comments of the
rmdir
manual page:http://www.php.net/rmdir