加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:53:10 所属栏目:PHP教程 来源:网络整理
导读:我有一个文件夹,里面装满了空文件夹和完整文件夹. 我想迭代所有这些,找出它们是否为空,如果是,则删除它们. 我已经看到了一些可以应用的问题,但我无法弄清楚整个解决方案: How can use PHP to check if a directory is empty? Finding empty folders recursi
我有一个文件夹,里面装满了空文件夹和完整文件夹.

我想迭代所有这些,找出它们是否为空,如果是,则删除它们.
我已经看到了一些可以应用的问题,但我无法弄清楚整个解决方案:

> How can use PHP to check if a directory is empty?
> Finding empty folders recursively and delete them recursively
> PHP script to loop through all of the files in a directory?

使用新的PHP5函数必须有一些简单的确定方法吗?

像(伪代码充满错误)

<?php
$dir = new DirectoryIterator('/userfiles/images/models/');
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
         if(!(new FilesystemIterator($fileinfo))->valid()) {
              rmdir($fileinfo);
         }
    }
}
?>

解决方法

这应该适合你:

在这里,我只使用glob()从特定路径获取所有目录(PHP 4> = 4.3.0,PHP 5).然后我遍历每个目录并检查它是否为空.

如果它是空的我用rmdir()删除它,否则我检查是否有另一个direcotry并用新目录调用该函数

<?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,$report);
            }
        }

    }


?>

removeEmptyDirs

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

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

描述

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

参数

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

返回值

None

举个例子:

如果$checkUpdated为TRUE,那么这样的结构将被完全删除:

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

结果:

- dir
   | - file.txt

如果它像默认值一样为FALSE,结果将是:

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

如果$report为TRUE,则会得到如下输出:

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

否则你没有输出

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读