0

I have a application which is generating images with file_get_contents and file_put_contents method from a dynamic image source. After creating the image the image is uploaded to a directory on my server. The problem I face is every time the image is generated and I refresh the page I see the old image appear. It shows the new image when I clear the cache.

How could I solve the issue?

<?php
$imagename = "img".$id.".png";
$host = $_SERVER['DOCUMENT_ROOT'];

$path     = $host.'/url/path/img/'.$imagename;
if(file_exists($path)) {
    //echo 'File already exists in that directory';
    unlink($path);
    $filehandler =  file_get_contents($imgurl);
    file_put_contents($path, $filehandler); 
}
else {
    $filehandler =  file_get_contents($imgurl);
    file_put_contents($path, $filehandler);
}
Aaron Meese
  • 316
  • 5
  • 16
  • "Cache busting" is the name that most solutions to this problem receive, in case you want to look for more information. – IOrlandoni Aug 30 '19 at 19:45

3 Answers3

1

It would always be better to use version as query Param to all images, js and css files. Using timestamp will not be as good since it will not be shown from cache if image is not updated. So in order to avoid additional overhead use version of images

That is, Initially

<img src="image.png?v1" />

Till now next updation occurs this should be the URL

Once it is updated, it should change to

<img src="image.png?v2" />
1

As the other answers already stated, simplest solution is to add a parameter to the image URL. To still leverage browser caching when the image is unchanged, you should not use a random value.

My recommendation is to use the modification time of the image file, e.g.

<img src="image.png?<?php filemtime('image.png'); ?>" />

This has the advantage, that you don't need to keep track of versions to increment a number or similar.

Lienhart Woitok
  • 426
  • 3
  • 10
0

This can be solved by adding random parameters to the image src, as shown here. For example, turn this:

<img src="image.png" />

Into this:

<img src="image.jpg?1222259157.415">

In the second src, the numbers after the question mark are the current timestamp. This is demonstrated in this answer, which sets the timestamp in JavaScript and appends it to the src using Date.now().

Aaron Meese
  • 316
  • 5
  • 16