Caching HTTP Headers in PHP

October 2nd, 2012 by Laeeq | 1 comment

Page caching is very important for a website as it speeds up repeated page views and saves a lot of traffic by preventing downloading content every page view. You can implement page caching by setting PHP header’s Cache-Control: max-age… property. The Cache control property will inform browser that the component won’t be changed for defined period. This will avoid unneeded further requests if browser already has the component in its cache. Most of modern browsers cache static files even without any cache control headers but if we can do it more efficiently by defining headers.

Here we will discuss how to control browser caching. First we will check whether page is cached or not. So make sure that the page is never cached:

  1. <?php
  2. $time = gmdate(“D, d M Y H:i:s”) . “ GMT”;
  3. header(“Expires: $time”);
  4. header(“Last-Modified: $time”);
  5. header(“Pragma: no-cache”);
  6. header(“Cache-Control: no-cache, must-revalidate”);
  7. ?>

Here we will set the amount of time to page cache. if you want page to be cached for a certain amount of time, set the expires header to a time in the future. Below example code will cache the output for 3600 seconds (1 hour).

  1. <?php
  2. $time_to_cache = 3600;
  3. $time = gmdate(“D, d M Y H:i:s”, time() + $time_to_cache) . “ GMT”;
  4. header(“Expires: $time”);
  5. header(“Pragma: cache”);
  6. header(“Cache-Control: max-age=$seconds_to_cache”);
  7. ?>

The Cache-Control header needs number of seconds to cache the file.

 

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • How much memory do PHP variables use?
  • Manipulating PHP arrays: push, pop, shift, unshift
  • 10 Super Useful PHP Code Snippets
  • Let’s play with php.ini file Configuration
  • 15+ regular expressions for PHP developers
  •  

     

    1. October 5th, 2012 at 07:50 | #1

      You can use Symfony HttpFoundation component : https://github.com/symfony/HttpFoundation to use easily your HTTP headers.

    1. No trackbacks yet.