HomeCoding & Programming

PHP: How to prevent image caching & prevent browser caching using HTTP headers

Like Tweet Pin it Share Share Email

Prevent Image Caching & Prevent Browser Caching

 

The Browser(s) saves a copy of a file (like a logo image) and uses this cached (saved) copy on each page that needs the same, but some time you will not need of this i.e you want that every image and CSS and java script should be reloaded when page loads, for implementing this we need some sort of techniques as below.

 

Simple way to disable image caching (Prevent Images Caching in Browsers) is to append time stamp with the image name.

 

eg.


<img src='image_name.jpg?<?php echo time() ?>' />

 

By this browser understand a new image at every call, but HTML parser understand ‘image_name.jpg’.

 

Prevent Browser Caching

By meta tag


<meta content="Fri, 20 Jan 1984 01:11:11 GMT"/>
<meta http-equiv="Pragma" content="no-cache" />

 

Here Meta tag tells the browser,cached copy of the page in back date.That means browser never get the cached page.

 

In PHP you can also achieve this approach by header function.
Here is the example.


<?php
header('Expires: Fri, 20 Jan 1984 01:11:11 GMT');
header('Pragma: no-cache');
?>

 

Or by the use of below code you can go


<?php
header('Expires: Fri, 20 Jan 1984 01:11:11 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
?>

 

By making cache disable your site visitor will always see the latest contents.

 

 

Comments (1)

  • Thanks for providing this. I kept getting cached images on a client’s site, so I did a search for “image cached on website” on Google, and I found this post. I added it to the site. Hopefully, my client won’t see the cached background image anymore.

Comments are closed.