仅删除PHP中的空文件夹和子文件夹

4
我有一个文件夹,里面装满了空的和非空的文件夹。
我想遍历它们,找出哪些是空的,如果是,则删除它们。我看到了一些相关的问题,但我无法找到完整的解决方案: 肯定有一些简单可靠的方法来做到这一点,可以使用新的PHP5函数吗?
类似以下内容(充满错误的伪代码):
<?php
$dir = new DirectoryIterator('/userfiles/images/models/');
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
         if(!(new \FilesystemIterator($fileinfo))->valid()) {
              rmdir($fileinfo);
         }
    }
}
?>

那么你想要一个使用DirectoryIterator的解决方案,还是可以使用glob或其他方法? - Rizier123
2
谢谢您的回答。我想要最优解决方案,考虑到我使用的是共享主机。因此,也许最少要求的解决方案就可以了? - chocolata
1个回答

8
这对你应该有用:
这里我使用了glob()(PHP 4 >= 4.3.0, PHP 5)从特定路径获取所有目录。然后,我遍历每个目录并检查它是否为空。
如果它是空的,我使用rmdir()删除它,否则我检查它是否有另一个目录,并使用新目录调用函数。
<?php

    function removeEmptyDirs($path, $checkUpdated = false, $report = false) {
        $dirs = glob($path . "/*", GLOB_ONLYDIR);

        foreach($dirs as $dir) {
            $files = glob($dir . "/*");
            $innerDirs = glob($dir . "/*", GLOB_ONLYDIR);
            if(empty($files)) {
                if(!rmdir($dir))
                    echo "Err: " . $dir . "<br />";
               elseif($report)
                    echo $dir . " - removed!" . "<br />";
            } elseif(!empty($innerDirs)) {
                removeEmptyDirs($dir, $checkUpdated, $report);
                if($checkUpdated)
                    removeEmptyDirs($path, $checkUpdated, $report);
            }
        }

    }


?>

removeEmptyDirs

(PHP 4 >= 4.3.3, PHP 5)
removeEmptyDirs — Removes empty directory's

void removeEmptyDirs( string $path [, bool $checkUpdated = false [, bool $report = false ]] )

Description

The removeEmptyDirs() function goes through a directory and removes every empty directory

Parameters

path
  The Path where it should remove empty directorys

checkUpdated
  If it is set to TRUE it goes through each directory again if one directory got removed

report
  If it is set to TRUE the function outputs which directory get's removed

Return Values

None

As an example:

If $checkUpdated is TRUE structures like this get's deleted entirely:

- dir
   | - file.txt
   | - dir
        | - dir

Result:

- dir
   | - file.txt

If it is FALSE like in default the result would be:

- dir
   | - file.txt
   | - dir  //See here this is still here

If $report is TRUE you get a output like this:

test/a - removed!
test/b - removed!
test/c - removed!

Else you get no output


1
非常感谢您详细的回答!我正在测试中,待会儿会跟您分享我的发现。这就是我喜欢 Stack Overflow 的原因! - chocolata
@maartenmachiels 没关系。如果有用,请让我知道。 - Rizier123
@maartenmachiels 奇怪,如果你不把第二个参数设为 true,它只会调用一次函数。但既然已经有一个测试成功了,也许这只是个偶然事件,如果你无法重现的话。(你能重现吗?) - Rizier123
第一次测试是没有子文件夹,启用了递归。第二次测试是有3个级别的子文件夹。将再试一次。 - chocolata
1
@maartenmachiels 嗯,真的很奇怪,我测试了一下,我无法重现内存错误(尝试使用600个文件夹),也没有找到不存在的目录的警告。(确保您的路径正确,或者尝试使用:./your path - Rizier123
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接