PDA

View Full Version : How do I prevent caching of image files generated by a CGI script?


WW.
03-14-2005, 11:53 PM
I have a CGI script that creates some PNG images. The file names of the images are based on the browser's IP address, eg "prefix.123.45.67.89.png". Typically a user will activate the script many times, and each time a new image is created, but with the same file name. (I prefer this to using a random number or the date to create the file name, because it prevents a proliferation of PNG files.)

The problem I have is that I can't seem to prevent the browser from caching the PNG file. This means the user must hit Reload while viewing the page in order to view the newly generated images.

I thought I could fix this by using another CGI script that would serve the images. E.g.

<img src="[the usual stuff]/cgi-bin/servepng.cgi?filename=file.png">

The script servepng.cgi outputs the current date, along with "Cache-control: max-age=0, must-revalidate", "Expires: -1", "Content-Type: image/png", and then it sends the PNG data.

This sometimes works, but sometimes it doesn't and the user must still hit Reload to see the new images.

Any suggestions? Am I doing something wrong? Is there a "correct" way to do this?

rwedge
03-15-2005, 01:24 AM
Add a random number to end of the URL - ie
<img src="[the usual stuff]/cgi-bin/servepng.cgi?filename=file.png?023654">
or make a new file name that includes a random number - file235467.png

/Bob

mlseim
03-15-2005, 02:23 AM
I thought this was interesting:

http://www.mnot.net/cache_docs/

WW.
03-15-2005, 03:31 AM
rwedge: Clever idea! I appended a random integer (preceded by an ampersand) to the servepng.cgi request, and it seems to prevent the caching. Thanks for the tip.

mlseim: Thanks for the link. Actually, I think that is the link where I first read about using the "Cache-control" and "Expires" headers.