Basically, I have a page where users can upload their profile picture. However, if they are replacing their current one, after the new one overwrites the old one, the old one still appears after the page reloads because presumably because the old one is cached.
In PHP, I have tried using:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: -1");
But it is not working in (at least) Google Chrome.
Any ideas what I 开发者_运维问答can do so that when I reload the page after the pic upload, it forces the browser to always pull the file from the server so it pulls the latest one?
Thanks!
I would advise you to append some sort of $_GET
-parameter to the image-url, like the following:
profile_user{user_id}.(jpg|png)?v={date('Ymdhis)}
(Note: pseudo)
The structure above wcould result in the following link:
profile_user001.png?v=20110804191700
New link = browser has to fetch a new image = victory.
As long as you're concerned about controlling the cache with HTTP headers, you must look if the client is using HTTP 1.1 or HTTP 1.0 as well as if there are proxies in between or not.
To generally specify that a resource should not be cached, you can consider the following headers:
header("Pragma: no-cache"); # HTTP 1.0
header("Cache-Control: no-cache"); # HTTP 1.1
header("Expires: Thu, 01 Dec 1994 16:00:00 GMT");
# With the two above, the last is not strictly necessary. Prefer a HTTP date in
# the past instead of -1 -OR- prefer 0 as it is specified how to deal with it.
For what can be cached and how, see Section 13.4 Response Cacheability and for the specific headers, please see Hypertext Transfer Protocol -- HTTP/1.1 Section 14 Header Field Definitions.
Setting the correct headers does not mean you're actually controlling the browsers cache in full. The only one who can do this is the user running the client. Any client can be configured to ignore these headers and just cache right away. E.g. pre-fetched content, whatever.
The only thing you can do then is to change the URI of resource (the profile picture in your case). E.g. each time the user changes her profile picture you can count up a revision counter and append it to the URI. That done will ensure that when the revisioned location of the profile picture is requested by the browser, the correct image will be displayed.
In case an old revision is requested, you must redirect to the latest revision. Redirect responses are most often not cached.
Using revisions will help that user-agents are still caching the pictures (which is nice for your bandwidth and the pages performance) while they always will display the latest revision.
You will need to send no-cache headers for the image file itself, not the PHP script. And your site performance will be bad if you disable caching and users will have to download the image on every request.
The standard practice is to use a new file name if the image is replaced, or at least append some kind of version to its name. e.g. image.jpg?v=xxx.
精彩评论