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

Posted by Danny Herran on Dec 30, 2012 in Backend, Frontend | 1 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.