Skip to content
Advertisement

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.

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

I’d like a library that does exactly the same thing in PHP, including generating the hashes at build time, not runtime.

I’ve seen an old same question on SO: hash css and js files to break cache. Is it slow? , but it never got an answer about how to do the md5 hash, so I’m asking again.

Advertisement

Answer

In PHP you’d usually use filemtime(). E.g.:

JavaScript

(You could use $timestamp directly as well)

If you want to have a md5 calculated from the file contents, you can use md5_file (linky), and do something like:

JavaScript

Or using CRC32, which is faster:

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement