Tag Archives: Caching

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

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.

[php]

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

[/php]

 

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

 

Prevent Browser Caching

By meta tag

[php]

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

[/php]

 

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]

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

[/php]

 

Or by the use of below code you can go

[php]

<?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’);
?>

[/php]

 

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