How to automatically force a cache refresh on CSS and JavaScript files with PHP?

Posted by on Dec 30, 2012 in CSS, PHP | One Comment

cache-internet-explorer-ie
There is your client, complaining that they can’t see the changes you just made to their website. You explain them that they need to delete their browser cache in order to properly visualize the modifications. They said they don’t know how, and this is when you lose your patience and decide for a more radical solution. We are developers right? there has to be something easier than explaining the client how to delete their cache. Read on for more.

My solution consists in a small PHP function that calls the CSS or JS file and appends a string based on the modification date of the file. So, if the file has been modified recently, the suffix string will change, forcing a cache refresh, otherwise, the file remains cached in the user’s browser as it is supposed to. Here is the magic…

function auto_version($file='')
{
    if(!file_exists($file))
        return $file;

    $mtime = filemtime($file);
    return $file.'?'.$mtime;
}

Now, wherever you have a stylesheet or javascript file call, just it this way:

<link type="text/css" rel="stylesheet" href="<?php echo auto_version('assets/main/css/styles.css'); ?>" />
<script src="<?php echo auto_version('assets/main/js/common.js'); ?>"></script>

PHP will lookup the file, get its modification date and append a suffix at the end of the filename call. It can’t get any easier than this. Luckily, your wont have any more complains of cached CSS or JS files from your clients.

1 Comment

  1. Idham Perdameian
    June 3, 2013

    If you using Apache web server, mod_expires should done.

    Reply

Leave a Reply