專案常需定期清理暫存、日誌或上傳目錄中過期的檔案(如超過 30 分鐘未處理的臨時圖片)。手動刪除不可行,需一個可排程執行的 PHP 腳本。
/**
* 刪除指定目錄下建立時間超過 $minutes 分鐘的檔案
* @param string $dir 目標目錄絕對路徑
* @param int $minutes 分鐘閾值
* @return int 刪除的檔案數
*/
function deleteOldFiles(string $dir, int $minutes = 30): int {
if (!is_dir($dir)) {
throw new InvalidArgumentException("目錄不存在: $dir");
}
$deleted = 0;
$cutoff = time() - ($minutes * 60);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $file) {
if ($file->isFile() && $file->getCTime() < $cutoff) {
@unlink($file->getPathname()) && $deleted++;
}
}
return $deleted;
}
// 使用範例:刪除 /var/www/temp 下 60 分鐘前的檔案
echo "已刪除 " . deleteOldFiles('/var/www/temp', 60) . " 個檔案";
SKIP_DOTS 自動跳過 . 和 ..filemtime 更適合「建立時間」判斷/usr/local/bin/cleanup_temp.php)crontab -e 設定定時任務:*/15 * * * * /usr/bin/php /usr/local/bin/cleanup_temp.php >> /var/log/cleanup.log 2>&1flock)防止重疊執行$file->getExtension() === 'tmp')