php删除子目录,php – 删除目录内容和子目录内容

我已经设置了一些PHP来删除一个目录,它的内容,以及任何子目录及其内容……我是PHP的新手,所以我绝对做错了或者以最低效的方式做某事.

寻找关于如何做得更好的一些参考或建议……

顺便说一句,这段代码工作正常.使用PHP 5.3.8.

chmod($main_dir, 0755);

if ($handle = opendir($main_dir)) {

while (false !== ($entry = readdir($handle))) {

$absolute_path = $main_dir.'/'.$entry;

if ($entry != "." && $entry != "..") {

chmod($absolute_path, 0755);

unlink($absolute_path);

//check if any folders exist, then delete files within

if (file_exists($absolute_path) && is_dir($absolute_path)) {

if ($child_handle = opendir($absolute_path)) {

while (false !== ($child_entry = readdir($child_handle))) {

$child_absolute_path = $absolute_path.'/'.$child_entry;

if ($child_entry != "." && $child_entry != "..") {

chmod($child_absolute_path, 0755);

unlink($child_absolute_path);

}

}

closedir($child_handle);

}

}

rmdir($absolute_path);

}

}

closedir($handle);

}

rmdir($main_dir);

有什么想法吗?非常感激!

我使用PHP 5.3.8

解决方法:

您可以使用RecursiveDirectoryIterator列出所有文件和文件夹,然后删除它们.请注意,您必须使用RecursiveIteratorIterator :: CHILD_FIRST,以便在文件夹之前删除文件.

$dir = __DIR__ . "/test";

$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);

$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);

foreach ( $ri as $file ) {

$file->isDir() ? rmdir($file) : unlink($file);

}

标签:php,delete-file,directory

来源: https://codeday.me/bug/20191003/1847708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值