简体   繁体   English

将文件md5哈希附加到PHP中的url

[英]Append file md5 hash to url in PHP

I want to append md5 hash to css and js files to able to long-term cache them in browser. 我想将md5哈希值附加到css和js文件中,以便能够将它们长期缓存在浏览器中。

In Python Django there is a very easy way to do this, static template tag https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#std:templatetag-static 在Python Django中,有一个非常简单的方法可以做到这一点,即静态模板标签https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#std:templatetag-static

I'd like a library that does exactly the same thing in PHP, including generating the hashes at build time, not runtime. 我想要一个在PHP中做完全相同的事情的库,包括在构建时而不是在运行时生成哈希。

I've seen an old same question on SO: hash css and js files to break cache. 我在SO上看到了一个旧的相同问题: 哈希CSS和JS文件来破坏缓存。 Is it slow? 慢吗? , but it never got an answer about how to do the md5 hash, so I'm asking again. ,但它从未得到有关如何执行md5哈希的答案,因此我再次询问。

In PHP you'd usually use filemtime . 在PHP中,您通常会使用filemtime Eg: 例如:

// $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);

(You could use $timestamp directly as well) (您也可以直接使用$timestamp

If you want to have a md5 calculated from the file contents, you can use md5_file ( linky ), and do something like: 如果要根据文件内容计算出md5,则可以使用md5_filelinky ),然后执行以下操作:

// getting the files md5
$md5 = md5_file($file_path);

// adding cache-busting string
$file_url .= '?m=' . $md5;

Or using CRC32, which is faster: 或使用速度更快的CRC32:

// getting the files crc32
$crc32 = hash_file ( 'crc32' , $file_path);

// adding cache-busting string
$file_url .= '?c=' . $crc32;

Take care of not doing it on a ton of files, or huge ones. 注意不要对大量文件或大型文件进行处理。 Unless you are deploying non-modified files constantly (which you shouldn't), the timestamp method is much faster and lighter, and good enough for the vast majority of purposes. 除非您不间断地部署未修改的文件(不应该这样做),否则timestamp方法会更快,更轻便,并且足以满足绝大多数目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM