Page 1 of 1

Refres /Reload image in browser after it is changed on server

Posted: 28 Apr 2015, 14:23
by PloMar
Hello,
I have a script that the user can upload and delete images on server. The issue I am running into is that when the user changes his image on server, the image doesn't change in browser when the page is reloaded; he /she must delete the browser cache to see the new image.
How can I make so to auto-refresh /Reload the image in browser when the user upload a new image (The image keeps the same name on server)? Any ideas?
- This is the code that adds the images in the page:

Code: Select all

<?php
for($i = $first_foto; $i <= $total_fotos; $i++) {  
  echo '<a href="'.$imgdir.'/'. $i .'_big.jpg" rel="next'.$id.'"><img src="'.$imgdir.'/'. $i .'_small.jpg" width="135" alt="&nbsp; '. $i .' &nbsp;" title="Foto '.$tip_anunt.'" alt="" /></a>';
}
?>

Refres /Reload image in browser after it is changed on server

Posted: 28 Apr 2015, 14:27
by Admin
Hi,
The simpliest way to force a refresh /reload of that image after upload is to add an unique "?hash" to the URL /SRC adress (src="image.jpg?h=unique_hash").
And serve the image with the header Cache-Control: no-store.
- in html meta tag:

Code: Select all

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
- or in PHP:

Code: Select all

header('Cache-Control: no-cache, no-store, must-revalidate');
Try this code in your script:

Code: Select all

<?php
$hash_img = '?h='. time();
for($i = $first_foto; $i <= $total_fotos; $i++) {  
  echo '<a href="'.$imgdir.'/'. $i .'_big.jpg'. $hash_img .'" rel="next'.$id.'"><img src="'.$imgdir.'/'. $i .'_small.jpg'. $hash_img .'" width="135" alt="&nbsp; '. $i .' &nbsp;" title="Foto '.$tip_anunt.'" alt="" /></a>';
}
?>