Manolo
Manolo

Reputation: 26360

Prevent browser-cached image

I'm developing a web application to transform images uploaded by the user. When the user changes the image, it is saved with an other name in the server and served again to the client, like an img tag. I have a problem when going back to the previous image. The actual image is deleted, and the new image is the previous. But when it is changed again by the user, the image shown isn't the new image, but the deleted image before go back. However, the image shown does not exist. I guess it is cached by the browser, but don't know how to prevent this.

Example:

$image1 = imagefirst.jpg
$image2 = imagechanged.jpg

//Going back:

$image3 = imagefirst.jpg
//imagechanged.jpg is deleted

//change again the image
$image4 = imagechanged.jpg

//serve to the client
<img src="imagefirst.jpg">    

//the image shown isn't the new one saved in the server, but the image deleted previously.

Upvotes: 0

Views: 224

Answers (2)

Amal Murali
Amal Murali

Reputation: 76646

A simple solution to this problem would be to add a random string to the image to force the browser to request for a new image every time. You can use uniqid(), rand(), or time() for this purpose:

echo "<img src='imagefirst.jpg?version=".time()."'/>";        

This will produce output similar to:

<img src='imagefirst.jpg?version=1378811671' />

As the query string is unique, the image would appear different to the browser.

Upvotes: 2

Alma Do
Alma Do

Reputation: 37365

Simply add random number to image's src property:

<!-- 759293475438 generated randomly each time -->
<img src='imagefirst.jpg?759293475438'/>

-to do this, you can use mt_rand() in PHP.

Upvotes: 2

Related Questions