Search code examples
phpimage.htaccesswebserverbrowser-cache

How do I prevent caching an image?


I have a virtual random image using .htaccess file:

#   .htaccess
<Files random.jpg>
    RewriteEngine On
    RewriteRule ^(.+)$ /random-image.php [QSA,L]
</Files>

and the following PHP:

<?php
    //  random-image.php
    $images=glob("images/*.jpg");
    $image=imagecreatefromjpeg($images[array_rand($images)]);
    header('Content-Type: image/jpeg');
    imagejpeg($image);
?>

and in HTML:

<img src="random.jpg">

This works well enough, but the browser has an annoying habit of caching the images, so I always get the same image rather than a new one.

I know that I can use JavaScript to append a random query string to the end of the src attribute, but that’s not always going to be an option.

Is there a way I can add additional headers, either in the PHP file or the .htaccess file to tell the browser not to cache the image and to always load from the server?


Solution

  • just put this inside tag in your .htaccess file

    Header set Cache-Control "max-age=0"