FireFox Caches Images When It Shouldn’t

I’ve recently come across a small annoyance in the firefox browser. I was creating a website that allows you to modify images so they can be printed. I had a caching issue when users would press back then change a setting and go forward again. A refresh would fix the issue. So FireFox was using the cache when I didn’t want to.

As usual first attempt was use some php code to specifiy the caching paramaters.

header(‘expires: Mon, 26 Jul 1997 05:00:00 GMT’);
header(‘cache-control: no-store, no-cache, must-revalidate’);
header(‘cache-control: post-check=0, pre-check=0′, FALSE);
header(‘pragma: no-cache’);

But to no avail, although IE responds extremely well Firefox didn’t. But i found that if the filename is the same as something in cache FireFox looks at the binary code and determines if anything has changed if it has it will reload the same image changing the cache.

This leads me to the solution, if you are writing PHP code then simply add this line to the end of the source attribute
<img src="image.jpg?t=<?php echo uniqid();?>" />

You can also achieve a similar process using javascript by utilising Math.rand() .

This tells firefox that the image is different when in reality it isn’t.

Remember Image Caching is a good thing except in instances such as this. Don’t restrict caching too much or you will find your bandwidth usage could jump quite a bit.

You can leave a response, or trackback from your own site.

2 Responses to “FireFox Caches Images When It Shouldn’t”

  1. Dale says:

    Thanks so much for this fix! It works great. I was trying to create an image verification page to prevent spam bots from filling out a form and firefox cached the images when I didn’t want it to. However, putting in the uniqid function as you suggested works perfectly. Thanks again!

  2. James says:

    Thank you ! A good idea!

Leave a Reply