萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 文章圖片管理:編輯時自動刪除已移除的圖片檔案

在 CMS 系統中,文章編輯時若使用者刪除了編輯器裡的圖片,資料庫雖更新了內容,但伺服器上的實體圖片檔案仍會殘留。本文示範如何在更新文章時,比對新舊內容的圖片差異,自動清理不再使用的圖片檔案。

核心邏輯

  1. 從資料庫取得舊文章內容,提取所有圖片檔名 → $oldimgs
  2. 從使用者提交的新內容提取所有圖片檔名 → $newimgs
  3. 計算差集 array_diff($oldimgs, $newimgs),得到需刪除的檔名
  4. 遍歷差集,呼叫 unlink() 刪除實體檔案

關鍵程式碼實作

1. 從文章內容提取圖片檔名

public function getimgsinarticle($content) {
    $temp = [];
    $imgs = [];
    // 匹配 http 開頭、以 jpg/gif/png 結尾的圖片網址
    preg_match_all('/http[^\d]*\d+[.](jpg|gif|png)/', $content, $temp);
    $temp = $temp[0];
    if (!empty($temp[0])) {
        for ($i = 0; $i < count($temp); $i++) {
            $imgs[$i] = pathinfo($temp[$i]);
            $imgs[$i] = $imgs[$i]['basename']; // 只取檔名
        }
        return $imgs;
    }
    return false;
}

正則說明: 匹配 http 開頭、非數字字元、至少一個數字、點號、副檔名。假設圖片命名格式如 201111291322589013.jpg(時間戳+隨機數)。

2. 比對新舊圖片並刪除差異

$oldimgs = $this->getimgsinarticle($oldarticledata['article_content']);
$newimgs = $this->getimgsinarticle($data['articlecontent']);
$newimgs = empty($newimgs) ? [] : $newimgs;

if ($oldimgs !== false) {
    $diff = array_diff($oldimgs, $newimgs);
    $diff = array_values($diff); // 重設索引
    if (!empty($diff)) {
        foreach ($diff as $imgname) {
            $this->delimg($imgname, ARTICLE_IMG_DIR);
        }
    }
}

3. 刪除圖片檔案

public function delimg($imgname, $dir) {
    @unlink($dir . '/' . $imgname);
    return true;
}

應用延伸

  • 刪除文章時:同樣呼叫 getimgsinarticle() 取得所有圖片,逐一刪除檔案後再刪除資料庫記錄。
  • 圖片目錄路徑:可用 realpath(__FILE__) 搭配相對路徑(如 ../uploads/article/)動態取得絕對路徑。
  • 正則改進:現有正則僅支援特定命名格式,實務上建議改用 /<img[^>]+src=[\"']([^\"']+)[\"']/i 搭配 parse_url() 取得 path,再用 basename() 取檔名,更通用健壯。
copyright © 萬盛學電腦網 all rights reserved