Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent browser image caching?

Tags:

php

caching

image

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?

like image 739
k_sel Avatar asked Jan 05 '12 20:01

k_sel


2 Answers

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.

like image 187
js-coder Avatar answered Nov 01 '22 13:11

js-coder


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)

like image 21
wIRELESS Avatar answered Nov 01 '22 13:11

wIRELESS