簡體   English   中英

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.

這是我的imagedeletescript.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天以上的randomNamedFolders,這不是我想要的。

如何獲取腳本以掃描上載文件夾中的所有隨機命名的文件夾,並刪除隨機命名的文件夾中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指出的那樣,即使在這種情況下只有一個條件,也請始終使用大括號( {} )作為條件。

你要復制你的while主要的內部循環loop ,或者您可以使用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);
        }
   }
}
(...)

最好的解決方案是實現遞歸。 您可以掃描所有目錄和子目錄,甚至更深的目錄。

<?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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM