How to block broswers from caching files

Block Browser Caching

By Jim Sbarra on July 29, 2009


Here is a little trick that can be helpful when browser caching becomes a problem. Technically we are not blocking the browser from caching, but instead tricking it into thinking that we are requesting a new file each time.

The Problem
Here's a couple scenarios that will help illustrate the solution. Let's say you have a flash file that accesses a dynamic xml sheet that may display different data everytime flash needs to access it. You don't want to show any old cached versions as this may not accurately reflect the data being requested.

Or lets say you have an image with the name myimage.jpg. However you are frequently changing myimage.jpg. So you don't want the browser to display an old cached version.

Here is the solution:
Any scripting language, PHP, ASP(.net), Javascript, etc has a function or a way to create a unique random number. Since I am primarily a PHP programmer I will demonstrate in PHP.

$token = md5(uniqid(rand(), true));

All that is going on here is we have a variable "$token" that is given an unique 32 digit alphanumeric value. So every time the page loads a new unique string gets created.

Now just assign that value to whatever file you don't want cached as a GET variable in the URI:

myimage.jpg?id=$token

So the HTML output of this would look like this:

<img src="myimage.jpg?id=1f3870be274f6c49b3e31a0c6728957f">

Now, because of the unique variable 'id' the browser thinks that it is accessing a different file. And there you have it. Real simple and works in every browser to make sure the most current version of the file gets displayed.

This works for all files. It does not have to be an image. XML sheets, SWF's, etc can all have this URI extention.

Heres the final code in PHP

//generate a random unique id everytime the browser refreshes
$token = md5(uniqid(rand(), true));

//output the image
echo '
<img src="myimage.jpg?id='.$token.'"> ';



Name:
Email (will not be published):
Url:
The difference of 12 - 8:
Message