CSS 文件中引用的背景圖、圖標等靜態資源更新後,瀏覽器緩存導致用戶看到舊版本。解決方案:為圖片 URL 自動添加版本查詢參數(如 bg.png?v=20240115),部署時批量更新 CSS 文件。
核心功能:
url(...) 中的圖片路徑<?php
/**
* CSSUpdate - CSS 靜態資源版本更新器
* 遍歷模版目錄,為 CSS 中圖片引用添加版本號,輸出到目標目錄
*/
class CSSUpdate {
private $csstmpl_path; // CSS 模版源目錄
private $css_path; // 目標輸出目錄
private $replacetags = []; // 需要處理的圖片副檔名
private $search_child = false; // 是否遞歸子目錄
private $convert_num = 0; // 處理文件計數
private $is_ready = 0; // 初始化狀態
/** 初始化
* @param string $csstmpl_path 源 CSS 目錄
* @param string $css_path 目標 CSS 目錄
* @param array $replacetags 圖片副檔名 ['png','jpg','gif']
* @param bool $search_child 是否遞歸子目錄
*/
public function __construct($csstmpl_path, $css_path, array $replacetags = [], $search_child = false) {
if (!is_dir($csstmpl_path) || !is_dir($css_path) || empty($replacetags)) {
$this->is_ready = 0;
} else {
$this->csstmpl_path = rtrim($csstmpl_path, '/');
$this->css_path = rtrim($css_path, '/');
$this->replacetags = array_map('strtolower', $replacetags);
$this->search_child = $search_child;
$this->is_ready = 1;
}
}
/** 執行更新 */
public function update() {
if ($this->is_ready === 0) {
$this->response('配置錯誤:源目錄、目標目錄或副檔名列表無效');
return;
}
$this->convert_num = 0;
$this->traversing($this->csstmpl_path);
$this->response("處理完成,共更新 $this->convert_num 個 CSS 文件");
}
/** 遞歸遍歷目錄 */
private function traversing($path) {
$handle = opendir($path);
if (!$handle) return;
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$curfile = $path . '/' . $file;
if (is_dir($curfile)) {
if ($this->search_child) {
$this->traversing($curfile);
}
} elseif ($this->checkExt($curfile)) {
// CSS 文件:生成目標路徑並處理
$dfile = str_replace($this->csstmpl_path, $this->css_path, $curfile);
$this->create($curfile, $dfile);
$this->response("$curfile -> $dfile 更新成功");
$this->convert_num++;
}
}
closedir($handle);
}
/** 檢查是否為 CSS 文件 */
private function checkExt($file) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
return $ext === 'css';
}
/** 核心處理:讀取模版、替換圖片 URL、寫入目標 */
private function create($tmplfile, $dfile) {
$css_content = file_get_contents($tmplfile);
foreach ($this->replacetags as $ext) {
// 匹配 url("xxx.ext") url('xxx.ext') url(xxx.ext)
// 版本號格式:?v=時間戳 或 ?v=哈希
$version = 'v=' . time(); // 或文件哈希:md5_file($img_path)
$pattern = '/url\([\'"]?([^\'")]+\.' . $ext . ')([\'"]?)\)/i';
$css_content = preg_replace_callback($pattern, function($matches) use ($version) {
$url = $matches[1];
// 已有版本參數則替換,否則追加
if (strpos($url, '?') !== false) {
$url = preg_replace('/\?v=[^&]*/', '?' . $version, $url);
} else {
$url .= '?' . $version;
}
return 'url("' . $url . '")'; // 統一雙引號
}, $css_content);
}
// 確保目標目錄存在
$dstDir = dirname($dfile);
if (!is_dir($dstDir)) mkdir($dstDir, 0755, true);
file_put_contents($dfile, $css_content, LOCK_EX);
}
/** 日誌輸出(可擴展寫文件) */
private function response($msg) {
echo date('[Y-m-d H:i:s] ') . $msg . "\n";
}
}
?>
<?php
require 'CSSUpdate.class.php';
// 配置
$tmplDir = __DIR__ . '/css_src'; // 開發環境 CSS 源碼
$distDir = __DIR__ . '/public/css'; // 生產環境輸出
$imageExts = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'ico'];
$updater = new CSSUpdate($tmplDir, $distDir, $imageExts, true); // true=遞歸子目錄
$updater->update();
?>
/* 處理前 (css_src/style.css) */
.header { background: url(../images/logo.png); }
.icon { background: url('sprite.jpg?v=123'); }
/* 處理後 (public/css/style.css) */
.header { background: url("../images/logo.png?v=1705312800"); }
.icon { background: url("sprite.jpg?v=1705312800"); }
// 替換 create() 中的版本生成邏輯
private function getVersion($imgRelPath) {
// 解析圖片絕對路徑
$imgPath = $this->resolveImagePath($imgRelPath);
if (file_exists($imgPath)) {
return 'v=' . substr(md5_file($imgPath), 0, 8); // 8位哈希
}
return 'v=' . time(); // 回退時間戳
}
// 正則回調中使用
$version = $this->getVersion($matches[1]);
// 在 create() 中添加
// 處理 @import
$css_content = preg_replace_callback(
'/@import\s+[\'"]([^\'"]+\.css)[\'"]/i',
function($m) { return '@import "' . $this->processImport($m[1]) . '";'; },
$css_content
);
// 保留 sourceMappingURL 不處理
// 或更新 sourcemap 對應關係
<?php
// 使用進程池並行處理
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmplDir));
$cssFiles = new RegexIterator($files, '/\.css$/i');
$pool = new Pool(4); // 4進程
foreach ($cssFiles as $file) {
$pool->submit(new CssProcessTask($file, $distDir, $imageExts));
}
$pool->shutdown();
?>
| 工具 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 本 CSSUpdate 類 | 零依賴、PHP 原生、易整合舊項目 | 功能單一、無壓縮、無 SourceMap | 遺留項目、簡單部署 |
| Gulp/Grunt + gulp-rev | 生態豐富、支持壓縮、SourceMap、並行 | 需 Node 環境、配置複雜 | 現代前端工程化 |
| Webpack + MiniCssExtractPlugin | 模塊化、Hash 命名、代碼分割、HMR | 學習曲線陡峭、構建慢 | 大型 SPA/SSR 項目 |
| Vite | 極速構建、原生 ESM、插件生態 | 較新、舊瀏覽器需 polyfill | 新項目首選 |
style.a1b2c3d4.cssexpires 1y + add_header Cache-Control "public, immutable"CSSUpdate 類為無法引入 Node.js 構建鏈的 PHP 項目提供了實用的靜態資源版本化方案,是從傳統部署向現代前端工程化過渡的橋梁。