1

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.

Community
  • 1
  • 1
slaweet
  • 385
  • 2
  • 17
  • MD5 is not a good choice for this. Simply use the mtime or if you truly care about content (why does the content change but not the mtime though?) use something super cheap like CRC32. – ThiefMaster Jan 12 '17 at 12:57
  • @ThiefMaster, MD5 beins slow is the reason I mentioned "generating the hashes at build time, not runtime", that way it's done in Django – slaweet Jan 12 '17 at 13:51

1 Answers1

4

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.

yivi
  • 42,438
  • 18
  • 116
  • 138
  • thank you for the suggestion, but I'd like to have the md5 sum based on the file content, not on it's modified date. Because on deploy all files get copied to the server (change timestamp), but not all must have been modified. – slaweet Jan 12 '17 at 12:50