[英]How to empty a directory in PHP except specific files
I'm creating a cron job that will autoflush the tmp directory everyday to make sure the tmp directory is not flooded with unwanted files.我正在创建一个 cron 作业,它将每天自动刷新 tmp 目录,以确保 tmp 目录不会被不需要的文件淹没。
However i want to delete all files and folders in the tmp directory except some files like .htaccess
i'm using the below code, but is giving an error但是我想删除 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
before this is used to run the below code which ran perfectly but also used to delete the .htaccess
file在此之前用于运行以下代码,该代码运行良好但也用于删除
.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());
}
Your error states that you can't delete non-empty dir.您的错误指出您无法删除非空目录。
So just check if dir is empty first.所以只需先检查 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.