How do I not cache image cache with HTML or PHP?

6

I'm creating a web page that is almost just image, every day I change the images of the page but their name remains the same. The browser is caching a lot and every time I update the images they do not change visually if you have already accessed the page in the browser.

    
asked by anonymous 13.06.2014 / 16:17

2 answers

11

Solution 1 - Serving images via PHP:

This is a solution to serve images so that they do not stay in the browser cache, setting the appropriate headers via PHP:

<?php
   header( 'Expires: Sat, 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( 'Pragma: no-cache' );

   header('Content-type: image/jpeg');
   readfile( 'minhaimagem.jpg' );
?>

Replacing minhaimagem.jpg with:

   readfile( '/caminho/para/imagem'.$_GET['img'] );

You can use URLs in this format, for example:

http://example.com/nocache.php/foto12.jpg
  

This is a simplification to illustrate the basic steps. Make sure to do an extra check in PHP to not give access to other files on the server.


Solution 2 - Changing SRC via PHP:

If the images only need to be updated on your page, you can do src like this:

echo '<img src="/link/para/imagem.jpg?'.date("YmdHis").'">';

In this way, every second the query string will change, forcing a rereading, however, always pointing to the same file paths on the server.

    
13.06.2014 / 20:21
3

I recommend using filemtime(...) with ? , similar to example of @Bacco , it returns the last of the file update, so the cache will only be updated if there are even modifications to it: / p>

<?php
//Pasta aonde ficam as imagens
define('ABSOLUTE_PATH', '/home/user/project/');
?>

<img src="/link/para/imagem.jpg?<?php echo filemtime(ABSOLUTE_PATH . 'link/para/imagem.jpg'); ?>">

And this way you'll still be able to benefit from the cache.

It is also possible to use a% of Apache% to set a cache time, for example one day after the last update.

First create a file named mod_expires in the folder where the images are located or in the root and place this content:

<IfModule mod_rewrite.c>
ExpiresByType image/gif "modification plus 1 day"
ExpiresByType image/jpeg "modification plus 1 day"
ExpiresByType image/png "modification plus 1 day"
</IfModule>

The .htaccess is used to define the cache by mimetype of the file, in this case I used ExpiresByType , image/gif and image/jpeg for the types image/png , .gif and .jpeg respectively. The .png indicates that the cache is generated from the last update of the file, as in your case once a day you change the files, modification adds a day to plus 1 day , so we will have the cache of one day .

    
22.12.2015 / 18:07