How to update image cache via PHP

Asked

Viewed 822 times

0

I have a thumbnail image on header.php, but when sending a request to update this image to another PHP page (which updates it in the database), it is not automatically updated on the page.

Obs.: I already inserted the following headers in header.php, unsuccessfully:

header("Pragma: no-cache");
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-cache, cachehack=".time());
header("Cache-Control: no-store, must-revalidate");
header("Cache-Control: post-check=-1, pre-check=-1", false);

1 answer

1


The most guaranteed way is to add a new parameter to the image link. Example: imagem.jpg?20170724. If I change it tomorrow it would look something like imagem.jpg?20170725.

You can try all these tricks with the header() but it won’t always work on all browsers as you might notice. In 18 years dealing with this, I’ve tried all of these header pragma, header expires and header macumba vela preta And just when I thought I’d found the right combination, a browser update would kick ass. I simply gave up and opted for the simplest and obvious that is to add the version of the file as parameter or the date and time of the last modification.

In the database, create a "date_modified" field and whenever you search for the image, also read this field to concatenate it in the URL.

Another technique used is to generate a file with a new unique name. So you wouldn’t have to worry about putting the date or version as the URL parameter. The downside of this is if the image is used for SEO because the previous one is given as Not found by search engines and the site loses rankings in the search for images (google images, for example).

It is worth noting that the technique with parameter does not update the existing cache. What happens is that the cache remains and is downloaded from the new file because for the browser, 1 different parameter is given as new file.

  • Hello @Danielomine, I am able to change temporarily by return Ajax, as follows: $('#foto-perfil img').attr('src', 'imagens/perfil/'+data);, date being a unique name, which is given the new image when it is changed. However, when you refresh the page again the loaded URL is the old one, even with the new name in the database. What could be happening?

  • Then it is the page cache itself and not the image.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.