2015-07-28 65 views
-1

我有一個cronjob,每天刪除所有未使用的文件,但我會希望走得更遠。我的文件是這種結構name_number.jpg,但一些文件具有這種結構name_.jpg刪除文件夾中的一些文件

目前我的腳本沒有區別,並刪除所有。我希望腳本刪除name_number.jpg而不刪除沒有編號的文件。

$days = 1; 
$path = './result/'; 

// Open the directory 
if ($handle = opendir($path)) 
{ 
    // Loop through the directory 
    while (false !== ($file = readdir($handle))) 
    { 
     // Check the file we're doing is actually a file 
     if (is_file($path.$file)) 
     { 
      // Check if the file is older than X days old 
      if (filemtime($path.$file) < (time() - ($days * 24 * 60 * 60))) 
      { 
       // Do the deletion 
       unlink($path.$file); 
      } 
     } 
    } 
} 

非常感謝您的回覆。

+1

變化'如果(filemtime($路徑$文件)<(時間(。 ) - ($ days * 24 * 60 * 60)))''if'filemtime($ path。$ file)<(time() - ($ days * 24 * 60 * 60))&& preg_match('@_ \ d + \。[a-zA-Z] {3} $ @',$ file))' – anonymous

回答

2

迭代器:

$days = 1; 

$fsi = new RegexIterator(
    new FilesystemIterator('/path/to/your/files'), 
    '(.+_\d+\.jpg$)' 
); 
/** @var SplFileObject $file */ 
foreach ($fsi as $file) { 
    if ($file->isFile() && $file->getMTime() < strtotime("-$days day")) { 
     unlink($file); 
    } 
} 

功能的方法:

$days = 1; 

array_map(
    function($file) use ($days) { 
     if (!is_dir($file) && filemtime($file) < strtotime("-$days day")) { 
      unlink($file); 
     } 
    }, 
    glob('/path/to/your/files/*_[1-9].jpg') 
); 

好老勢在必行:

$days = 1; 

foreach (glob('/path/to/your/files/*_[1-9].jpg') as $file) { 
    if (!is_dir($file) && filemtime($file) < strtotime("-$days day")) { 
     unlink($file); 
    } 
}; 
相關問題