繁体   English   中英

如何清空PHP中除特定文件外的目录

[英]How to empty a directory in PHP except specific files

我正在创建一个 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());
        }

您的错误指出您无法删除非空目录。

所以只需先检查 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; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM