Sign in to follow this  
Dom_152

[web] Browser caching

Recommended Posts

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 javascript 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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this