【问题标题】:How to empty a directory in PHP except specific files如何在 PHP 中清空除特定文件之外的目录
【发布时间】:2020-06-04 10:53:51
【问题描述】:

我正在创建一个 cron 作业,它将每天自动刷新 tmp 目录,以确保 tmp 目录不会被不需要的文件淹没。

但是我想删除 tmp 目录中的所有文件和文件夹,除了 .htaccess 之类的一些文件,我正在使用下面的代码,但给出了错误

    $filesToKeep = array(
                            '.htaccess'
                            // 'i.php',
                            // 'c.php'
                        );

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {
            if (! in_array($file, $filesToKeep))
                {
                    if ($file->isDir())
                        rmdir($file->getRealPath());
                }
            else
                unlink($file->getRealPath());
        }

Warning: rmdir(D:\Development(s)\Project(s)\blog\app\tmp\error_pages): Directory not empty

在此之前用于运行以下代码,该代码运行良好但也用于删除.htaccess文件

    $dir = '../tmp/';

    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

    foreach($files as $file)
        {

            if ($file->isDir())
                rmdir($file->getRealPath());
            else
                unlink($file->getRealPath());
        }

【问题讨论】:

  • 所以这意味着你的error_pages 包含一些像.htaccess 这样的文件,你不能删除它。
  • no error_pages 中只有一个名为 404.php 的文件
  • 所以它不是空的,你不能删除它。先检查dir是否为空,然后删除。
  • 如何修改代码?我有点困惑!

标签: php .htaccess


【解决方案1】:

您的错误表明您无法删除非空目录。

所以先检查 dir 是否为空。

$filesToKeep = ['.htaccess', /*'i.php', 'c.php'*/];

$dir = '../tmp/';

$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);

foreach ($files as $file) {
    if (in_array($file->getBasename(), $filesToKeep)) {
        continue;
    }

    if (!$file->isDir()) {
        unlink($file->getRealPath());
        continue;
    }

    if (isEmptyDir($file->getRealPath())) {
        rmdir($file->getRealPath());
    }
}

function isEmptyDir($dir){
    $files = scandir($dir);

    // $files contains `..` and `.` along with list of files
    return count($files) <= 2; 
}

【讨论】:

  • 代码工作正常,但也删除了.htaccess文件
  • @AkshayShrivastav 检查更新。检查名称是否在白名单中时,您似乎缺少$file-&gt;getBasename()
猜你喜欢
  • 1970-01-01
  • 2022-12-01
  • 2019-12-04
  • 2010-10-26
  • 2014-01-25
  • 1970-01-01
  • 2012-08-08
  • 2013-01-12
  • 2021-06-18
相关资源
最近更新 更多