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.

Scroll to top