在 CMS 系統中,文章編輯時若使用者刪除了編輯器裡的圖片,資料庫雖更新了內容,但伺服器上的實體圖片檔案仍會殘留。本文示範如何在更新文章時,比對新舊內容的圖片差異,自動清理不再使用的圖片檔案。
$oldimgs$newimgsarray_diff($oldimgs, $newimgs),得到需刪除的檔名unlink() 刪除實體檔案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(時間戳+隨機數)。
$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);
}
}
}
public function delimg($imgname, $dir) {
@unlink($dir . '/' . $imgname);
return true;
}
getimgsinarticle() 取得所有圖片,逐一刪除檔案後再刪除資料庫記錄。realpath(__FILE__) 搭配相對路徑(如 ../uploads/article/)動態取得絕對路徑。/<img[^>]+src=[\"']([^\"']+)[\"']/i 搭配 parse_url() 取得 path,再用 basename() 取檔名,更通用健壯。