我想将md5哈希附加到css和js文件,以便能够在浏览器中长期缓存它们。
在Python Django中有一种非常简单的方法,静态模板标记https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#std:templatetag-static
我想要一个在PHP中完全相同的库,包括在构建时生成散列,而不是运行时。
我在SO上看到了一个同样的老问题: hash css and js files to break cache. Is it slow?,但它从来没有得到关于如何进行md5哈希的答案,所以我再问一次。
答案 0 :(得分:2)
在PHP中,您通常使用filemtime
。 E.g:
// $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;
注意不要在大量文件或大文件上执行此操作。除非您不断地部署未修改的文件(您不应该这样做),否则时间戳方法更快更轻,并且足以满足绝大多数目的。