Server side forced reload of a cached file in browser

With the advent of modern browsers, web pages are using more and more javascript and stylesheets to make applications work faster and look better. And this is achieved with caching the Javascript, images and CSS files in the browser cache in user’s machine. This is great for speeding up page load for end user, but this causes problems when we update these files on server but browser keeps using the old file from cache.

To trick browser to load the same file again we can add a parameter with the file name like my_javascript.js?v=123 and keep changing the value of v whenever the file changes. This tricks browser as new URL and it reloads the same file again with changes. But this poses another issue to update the include links every time whenever the corresponding file is changed.

So here is an automated solutions for PHP developers. Just define following function in a location where it is accessible in all scripts specially View files – which generate the HTML.


function auto_version($file) {
if(!file_exists($file))
return $file;
$mtime = filemtime($file);
return $file."?v=" . $mtime;
}

Now modify your include links as given below:

<script type="text/javascript" src="<?php echo auto_version("js/custom.js") ?>"></script>

Now you never have to update the include link to force the file reload, it will automatically check the file modification timestamp and append that to URL.

2 thoughts on “Server side forced reload of a cached file in browser

  • Hi,
    I am bit of a dummy when related to php and not sure where to add the above code? I am trying to update my css stylesheet but cannot see any changes, not even when I clear cookies and caches on my browser.
    Any help is much appreciated.

  • Barbara, In most simple setup, you can add the above function in a php block on the top of the file where you want to use it. Then put the above line to include CSS in the HTML head as you do for other CSS files. Just remember to change the file name to the actual file you want to include.
    I hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *