首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實現圖片自動清理:定時刪除 N 天未訪問的靜態文件

     編輯:PHP 相關知識

場景痛點

項目運行久了,上傳目錄堆積大量廢棄圖片,佔用磁盤空間且難以手動清理。本文提供一個「設置即運行」的 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);
                }
            }
        }
    }
}

關鍵點解析

  • fileatime() vs filemtime():本例使用「最後訪問時間」,若需按「最後修改時間」清理,請改用 filemtime()。
  • 錯誤抑制 @unlink:避免權限不足等情況拋出警告中斷腳本。
  • 日誌記錄採用 error_log(..., 3, $file):高效追加寫入,無需手動 fopen/fwrite。
  • 遞歸深度風險:極深目錄結構可能導致棧溢出,生產環境建議改用 RecursiveDirectoryIterator 迭代器。

部署建議

  1. 將腳本放置於項目根目錄或獨立 cron/ 目錄。
  2. 編輯 crontab:0 3 * * * /usr/bin/php /path/to/clear_image.php >/dev/null 2>&1。
  3. 定期檢查 Imglog/ 目錄下的日誌文件,確認清理效果。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved