ProTip: A PHP Cache Buster for CSS + JavaScript Assets

Published on July 1st, 2016

ProTip: A PHP Cache Buster for CSS + JavaScript Assets image

I know that it's extremely rare for me to post about PHP... but hear me out.

I've worked with a few clients who will about halfway through their project receive link from me to get a first-look at their project in development. Throughout the project they'll get updates from me about going back to this same development preview link, but the problem I have experienced is that their browser has previously cached (now stale) versions of the CSS and JavaScript files - meaning my client is seeing the latest HTML and markup, but stale CSS + JavaScript.

This does not make for an awesome start to a preview + status call.

Bust Those Caches

The easiest and quickest (and dirtiest?) solution I've found to remedy this issue is to use a PHP-driven UTC timestamp URL parameter cache buster on files which tend to be cached by my clients' computers. Check it:

<link rel="stylesheet" type="text/css" href="path/to/stylesheet.css?r=<?php echo time(); ?>" />

<script type="text/javascript" href="path/to/javascript.js?r=<?php echo time(); ?>"></script>

That little <?php echo time(); ?> will barf out a UTC timestamp, ensuring the URL is always "unique" (enough) to bypass the browser's cache and always pull the latest version.

The parameter name r bears no significance here - in this example it stands for "random," but you could name that /?random= or /?cachebuster= or /?fhqwhgads= if you really wanted to.

You might not need this for all your clients - but it tends to be extremely useful for clients who might not know how to clear their browser cache.

Headshot of Mike Zarandona

Huge nerd, hobby collector, happy husband & dad. The personal website of Mike Zarandona.

Optimizing CSS Inheritance
Front-End Toolbelt: `--allow-empty`

© 2023 Mike Zarandona