Noiselabs Consulting

Noiselabs Consulting


Software Consultancy

Share


Tags


How to prevent caching (force image reload) in PHP and/or JavaScript/jQuery

If you are using images generated on-the-fly by a PHP script (or another server language), like I'm doing on my web application, you surely do not want images to be read from cache as your users will be seeing the same first generated image (saved into cache) and not the new generated versions.

You can play with some header commands and build a function like this...

function cacheKiller() {
	header("Cache-Control: no-cache, must-revalidate");
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
}

...but this will work for the whole page and not only for images.

So, to make sure the images shown are always up-to-date the simple way is to add a query section with a random number to the image URL in order to make the browser think that this is a different image, while keeping the same name.

PHP

In PHP it works like this:

// Generate a number that will never be repeated using the time function
// that "returns the current time measured in the number of seconds since
// the Unix Epoch (January 1 1970 00:00:00 GMT)"
$cachekiller = time();

// Include the generated number in the image URL
<img src="path/to/image.png?{$cachekiller}"></pre>

JavaScript / jQuery

If the image URL is built using JavaScript/jQuery the Math function is good choice to generate a random number.

// Generate random number between 1 and 1000.
var cachekiller = Math.floor(Math.random()*1001);

$("#thumbnail").attr("src", "path/to/image.png?"+cachekiller);
View Comments