Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP force refresh image

Tags:

php

I'm creating an input form that allows users to upload an image. Once it has been submitted the user is returned to the form with a conformation bit at the top.

Any image that has been submitted is then previewed via a query to a MySQL database that stores the URL of the image. However, if the user uploads a photo, it is previewed, and then they decide to change that photo and resubmit the form, when it takes you back to the form the new photo doesn't show unless you manually press refresh on the browser.

Is there any way of forcing a refresh/cache deletion or refresh for that specific image rather than the whole page?

Thanks

like image 551
DorianHuxley Avatar asked May 13 '13 16:05

DorianHuxley


2 Answers

Add the modified date to the end of the image as a query.

<img src="/images/photo.png?=1239293"/>

In PHP

<img src="/images/photo.png?=<?php echo filemtime($filename)?>"/>
like image 62
Reactgular Avatar answered Sep 19 '22 18:09

Reactgular


The trick here is to tell the browser to not cache the content. You can do this by putting these statements before ANYTHING else (no whitespace or anything!)

<?php
header("Expires: Mon, 26 Jul 1997 05: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");
?>

Depending on how you're loading the image, you can also do a javascript refresh of the image using jQuery.

like image 38
Christian Stewart Avatar answered Sep 21 '22 18:09

Christian Stewart