8

What is the best way to prevent the browser from caching images in PHP?

I've tried the header( method:

header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

But nothings seems to work save for manually clearing the browser's cache.

I have images that are replaced with the same name, such as avatar.png as an updateable avatar for the user, but when it is updated, the browser holds onto an old version.

Even when the original is deleted and a new one is added, the browser still holds onto the old avatar.png.

Any thoughts?

k_sel
  • 775
  • 2
  • 8
  • 5

4 Answers4

20

Just put a random parameter at the end of the image URL. A timestamp can also be used very well for this.

For example in PHP:

"http://domain.com/img.png?t=" . time();

The browser will always load this image new. You should use it with care though, it will make loading times slower.

js-coder
  • 8,134
  • 9
  • 42
  • 59
  • Worked like a charm! Thanks for the tip! – k_sel Jan 06 '12 at 06:20
  • 3
    Bad idea. Forces a reload from the server every single time the image is displayed, which is completely unnecessary. And also you've not mentioned setting headers to prevent caching, so each and every one of those reloaded images is going to get separately cached, on your machine and also on any intermediate caches between you and the server. wIRELESS's suggestion is MUCH better, and just as simple. – Doin Mar 15 '14 at 22:02
6

As soon as you are inserting your own image there is no need to prevent picture caching each time. You can just use filemtime($imgPath) to check last picture change time.

E.g: 'http://example.com/img.jpg?last_picture_update=' . filemtime($imgPath)

wIRELESS
  • 196
  • 3
  • 3
  • 1
    Actually most of the cache busting mechanisms use a similar approach. Care must be taken that some proxy servers disregard the query part so its a far better idea to use something like this `"http://example.com/img" . filetime($imgPath) . ".jpg"` and then strip away the numeric part with `.htaccess`. –  Jul 01 '14 at 13:23
2

Within the same browsing session, if you use the same IMG src, the browser will often re-use its retained-in-memory copy of an image regardless of caching settings. That seems to be what's happening to you here.

I've summarized some common solutions to the "update an image" problem here.

Community
  • 1
  • 1
Doin
  • 7,545
  • 4
  • 35
  • 37
-2

thank you, this Run for me like this

not run<

echo "&lt;img src='gambarLimas.jpg'><br>"; 

run well

echo "&lt;img src='gambarLimas.jpg?t=".time()."'><br>"; 
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • Hey Dody, try to code tags to separate code, and explain why your solution works with a comment. Welcome to the community. – ksloan Nov 28 '16 at 19:01