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.:

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

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

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

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

Or using CRC32, which is faster:

// 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.

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