在PHP中,您通常會使用filemtime
。例如:
// $file_url is defined somewhere else
// and $file_path you'd know as well
// getting last modified timestamp
$timestamp = filemtime($file_path);
// adding cache-busting md5
$file_url .= '?v=' . md5($timestamp);
(你可以直接使用$timestamp
爲好)
如果你想擁有從文件內容計算MD5,你可以使用md5_file
(linky),並做一些事情,如:
// getting the files md5
$md5 = md5_file($file_path);
// adding cache-busting string
$file_url .= '?m=' . $md5;
或者使用CRC32,這是更快:
// getting the files crc32
$crc32 = hash_file ('crc32' , $file_path);
// adding cache-busting string
$file_url .= '?c=' . $crc32;
請注意不要在大量文件或大型文件上執行此操作。除非您經常部署未修改的文件(您不應該這麼做),否則時間戳方法會更快更輕,並且足夠滿足絕大多數目的。
MD5對此不是一個好的選擇。簡單地使用mtime,或者如果你真的關心內容(爲什麼內容會改變但不是mtime?)使用像CRC32這樣的超便宜的東西。 – ThiefMaster
@ThiefMaster,MD5 beins slow是我提到的「在構建時生成哈希,而不是運行時」的原因,這種方式在Django中完成 – slaweet