PHP force refresh image

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?


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

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


<img src="/images/photo.png?=<?php echo filemtime($filename)?>"/>

Solution 2

In PHP you can send a random number or the current timestamp:

<img src="image.jpg?<?=Date('U')?>">


<img src="image.jpg?<?=rand(1,32000)?>">

Solution 3

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!)

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.

Solution 4

This worked great for me:

image.jpg?=<?php echo rand() . "\n";?>

Solution 5

You could replace the current image by a new one using JavaScript:

    <div id="imageHolder">this is where the image will show</div>
    <script type="text/javascript">
    function myfunction(){
    document.getElementById("imageHolder").innerHTML="<div id=\"imageHolder\"><img src='imagefolder/imagename.jpg' alt=''/></div>";

You need to trigger the function myfunction after completing the upload of course …

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply