views:

64

answers:

3

I have a listing of items, that also contains an image thumbnail. Sometimes I need to change the thumbnail image, but keep the filename the same. Is there a way to force the browser to download the newly uploaded image, instead of grabbing one from the browser cache?

This is very pertinent when people update their avatars, which causes confusion for some users, who keep seeing their old avatar, until they clear the browser cache, or restart the browser.

A: 

You can invalidate the cache for an entire page by altering the headers:

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
TomWilsonFL
This will unfortunately make caching of the file impossible, increasing the page load time and bandwidth cost.
Emil Vikström
Then only do it after an upload?
Kristoffer S Hansen
A: 

When sending out the image, make sure not to send any Expires header. Also consider sending this cache header:

Cache-Control: must-revalidate

This will make the browser ask your server for the image every time. Watch for an If-Modified-Since header in the request; if the image is not modified, answer with an 304 HTTP code.

This whole procedure (must-revalidate, If-Modified-Since, 304 answer) will make it possible for the browser to cache the image content but at the same time ask your server if the file has changed.


Another, maybe simpler, solution is to only set an Expires header a short time in the future, for example ten minutes, and inform the user of the ten minute delay. This will speed up most page loads since there's no need to do any HTTP request for the image at all.

Emil Vikström
What do you mean by "when sending out the image"? After I upload an image, and use header("Location:whatever.php"); ?
Yegor
No, I mean when someone requests the image file, i.e. does an HTTP request for /example/image.jpg
Emil Vikström
A: 

You can use the modification time of file:

<?

$filename = 'avatar.jpg';
$filemtime = filemtime($filename);

echo "<img src='".$filename."?".$filemtime."'>";

//result: <img src='avatar.jpg?1269538749'>

?>

when the file is modified will clear the client cache

Leo
Not possible in many cases due to cached nature of HTML code.
Yegor
can tell me which cases?
Leo
Where a cache generated HTML code into the DB, which gets updated once every few days
Yegor