views:

1156

answers:

3

Hi there

I generate some images using a PHP lib. Sometimes the browser don't load the new generated file. How can I disable cache just for images created dynamically by me?

obs I have to use same name for the created images

+4  A: 

Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you'll need several headers to get the desired effect on a range of browsers.

    header("Pragma-directive: no-cache");
    header("Cache-directive: no-cache");
    header("Cache-control: no-cache");
    header("Pragma: no-cache");
    header("Expires: 0");
lhunath
this will applay to the whole page....I can't disable cache for one image only(a specific image from that page)?
dole doug
@dole doug: Those are HTTP headers of your IMAGE, not your PAGE...
lhunath
@Ihunath. It didn't work for me. I guess it doesn't apply to images..
Thorpe Obazee
@Thorpe: It applies to HTTP responses. What is contained in the response is irrelevant. Whether it's image data, HTML data or whatever else. If it didn't work, you probably didn't do it right. Check the HTTP headers on your response to see if they have been correctly assigned.
lhunath
+6  A: 

A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

So, for example -

<img src="image.png" />

Would become

<img src="image.png?dummy=8484744" />

Or

<img src="image.png?dummy=371662" />

From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.

The random number generation can happen either on the server when serving the page (just make sure the page itself isn't cached...), or on the client (using JavaScript).

You will need to verify whether your web-server can cope with this trick.

Hexagon
Instead of random numbers, use the timestamp that the data changed or a version number of the reflected data.
lhunath
A: 

A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

So, for example

Thank you for this answer! it's very useful to me. Thank u!

luuanhquyen