項目運行久了,上傳目錄堆積大量廢棄圖片,佔用磁盤空間且難以手動清理。本文提供一個「設置即運行」的 PHP 腳本,自動刪除指定天數未被訪問的文件,並記錄操作日誌。
<?php
/**
* 圖片清理計劃:刪除 7 天未訪問的文件
* 部署建議:加入 crontab 定時任務,如每天凌晨 3 點執行
*/
$sRootPath = dirname(__FILE__);
$dir = $sRootPath . DIRECTORY_SEPARATOR . 'upload'; // 目標目錄
$iTimeLine = strtotime("-7 day"); // 時間閾值
$sLogDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Imglog';
$sLog = $sLogDir . DIRECTORY_SEPARATOR . date("Ymd") . '.txt';
// 確保日誌目錄存在
if (!file_exists($sLogDir)) mkdir($sLogDir, 0777, true);
_clearFile($dir, $iTimeLine, $sLog);
// 記錄執行結束
$sEnd = 'AT' . "\t" . date("Y-m-d H:i:s") . "\t" . 'EXEC OVER' . "\n";
error_log($sEnd, 3, $sLog);
/**
* 遞歸遍歷目錄,刪除超時文件
* @param string $sPath 文件/目錄路徑
* @param int $iTimeLine 訪問時間閾值(時間戳)
* @param string $sLog 日誌文件路徑
*/
function _clearFile($sPath, $iTimeLine, $sLog) {
if (is_dir($sPath)) {
$fp = opendir($sPath);
while (false !== ($fn = readdir($fp))) {
if ($fn == '.' || $fn == '..') continue;
$sFilePath = $sPath . DIRECTORY_SEPARATOR . $fn;
_clearFile($sFilePath, $iTimeLine, $sLog); // 遞歸處理
}
closedir($fp);
} else {
// 跳過 . ..
if ($sPath != '.' && $sPath != '..') {
$iLastView = fileatime($sPath); // 獲取最後訪問時間
if ($iLastView < $iTimeLine) {
if (@unlink($sPath) === true) {
$str = date("Y-m-d H:i:s") . "\t" . 'success del file : [' . $sPath . ']' . "\n";
error_log($str, 3, $sLog);
}
}
}
}
}
filemtime()。RecursiveDirectoryIterator 迭代器。cron/ 目錄。0 3 * * * /usr/bin/php /path/to/clear_image.php >/dev/null 2>&1。Imglog/ 目錄下的日誌文件,確認清理效果。