Using PHP to avoid caching of CSS and javascript

Here’s a handy tip which I’ve been using recently. Often when developing sites you’ll make a change to an external CSS file, then reload the page only to find the change you made isn’t visible (or more likely, you’ve sent the link to the client who emails back saying ‘Still looks the same to me!’). Rather than having to explain caching to your client, there’s some simple PHP code you can use to get around this.

The key to the solution is the filemtime PHP function. Give it the path of a file and it’ll return a timestamp of when the file was last modified. To use in your website, you would embed the following PHP into the of your HTML :

$css_file = 'css/main.css';
if (is_file($css_file)) {
  echo ‘<link rel="stylesheet" rev="stylesheet" href="’.$css_file.'?v='.filemtime($css_file).'" media="screen" />';
}

This will output something like -
<link rel="stylesheet" rev="stylesheet" href="css/main.css?v=1250171883" media="screen" />

Each time the value of the v variable being passed to the CSS file changes (i.e. when you make a change to the CSS file), the browser will load in a fresh copy.

This method also works well when including external javascript files - you’d simply echo out a <script> tag instead of the <link> tag.

Posted 11 months, 2 weeks ago

I believe you could drop the v= and achieve the same effect :

css/main.css?1250171883

It’d also be nice to wrap this up into a little view helper (Rails does this), so you could output the style element with:

<pre>echo stylesheet_link_tag('main.css');</pre>

Chris · www · 11 months, 2 weeks ago

Very handy tip mate - sometimes the simple things are the most useful!

Steve Woods · www · 10 months, 3 weeks ago

Commenting on this post has been disabled.