[web] Browser caching

Started by
3 comments, last by markr 16 years, 9 months ago
How can I prevent the clients browser from caching the servers response to a request. I need the client to the update frequently but I don't want it to use a cached version of the servers response as, chances are, things will have changed by that time. I am also having trouble with the browser caching &#106avascript files which isn't good because if I update them the browser will use it's cached version rather than the new one which causes things to break. The same applies to images. If I update an existing image the end users browser will display the old, cached version. I think I have to use the PHP header() function but I'm not sure what to put in it. EDIT: I've just read something about adding random numbers to the end of a URL to prevent the browser loading a cached version but I'm not sure I understand what it means.
It's not a bug... it's a feature!
Advertisement
It means that you add a random query string after the image source. Like this:

<img src="image.jpg?<?=microtime()?>" />

Even if this particular number isn't random it still won't be the same when you reload the page and prevents browser caching.
Don't add a random query string to your requests.

Just use an appropriate "Expires:" header in your HTTP responses, and the browser will get it again once it's expired.

See the appropriate RFCs for more details.

Mark
Straight from the PHP manual on header():

Quote:
PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past

<hr />
Sander Marechal<small>[Lone Wolves][Hearts for GNOME][E-mail][Forum FAQ]</small>

I can't stress how much, you must RESEARCH your techniques appropriately (e.g. read relevant RFCs),

You should TEST the techniques in various browsers / contexts,

Then make an INFORMED decision what technique to use on the basis of your data.

Cheers
Mark

This topic is closed to new replies.

Advertisement