PHP 删除未知子目录中的图像


PHP delete images in unknown subdirectories

我正在寻找一种在随机命名的文件夹中删除超过 30 天的图像的方法。

我的服务器上有以下目录结构:

mainDirectory (folder)
  imagedeletescript.php (script)
  images (folder)
    uploads (folder)
      randomNamedFolder (folder)
      randomNamedFolder (folder)
      randomNamedFolder (folder)
      randomNamedFolder (folder)
      etc.

这是我的图像删除脚本.php:

<?
$days = 30;
$dir = dirname ("/images/uploads");
$nofiles = 0;
    if ($handle = opendir($dir)) {
    while (( $file = readdir($handle)) !== false ) {
        if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
            continue;
        }
        if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
            $nofiles++;
            unlink($dir.'/'.$file);
        }
    }
    closedir($handle);
    echo "Total files deleted: $nofiles 'n";
}
?>

上面的脚本将删除上传文件夹中超过 30 天的 randomNamedFolder,这不是我想要的。

如何让脚本扫描上传文件夹中的所有随机命名文件夹,并删除随机命名文件夹中超过 30 天的所有图像?

您可以使用 glob()stat() 的组合:

$days = 30;
$images = glob('/images/uploads/{*.png,*.jpg,*.bmp}', GLOB_BRACE);
foreach ($images as $image) {
    $stats = stat($image);
    if ($stats[9] < (time() - (86400 * $days)) {
        unlink($image);
    }
}

这将在文件夹/images/uploads中查找扩展名为 .png.jpg.bmp 的文件(无论其深度如何),并检查它们是否超过 30 天。

提示:虽然与您的问题没有直接关系:正如@D4V1D所指出的,即使在这种情况下只有一个条件,也请始终使用大括号 ( {} ) 表示您的条件。

最好的解决方案是实现递归。您可以扫描所有目录和子目录,甚至更深的目录。

<?php
     $days = 30,$deleted = 0;
     function delete_old_files($dir) {
       global $days,$deleted;
       if(!is_dir($dir)){
         return;
       }
       $files = preg_grep('/^([^.])/', scandir($dir));
       foreach($files as $file) {
         $path = $dir.'/'.$file;
         if(is_dir($path)){
            //the current file is a directory, re-scan it
            delete_old_files($path);
            continue;
         }
         if(time() - filemtime($path) > $days * 86400){
           unlink($file) ? ++$deleted : null;
         }
       }
       return $deleted;
     }
     //now call this function
     delete_old_files("/images/uploads");

您必须在主loop中复制while循环,或者您可以通过以下方式使用 scandir()glob()

(...)    
while (( $file = readdir($handle)) !== false ) {
    if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
        continue;
    }
    $curDir = "$dir/$file";
    foreach( scandir( $file ) as $rndFile ) {
        if ( $rndFile == '.' || $rndFile == '..' || is_dir("$curDir/$rndFile") ) continue;
        if ((time() - filemtime("$curDir/$rndFile")) > ($days *86400)) {
            $nofiles++;
            unlink($dir.'/'.$file);
        }
   }
}
(...)