Caching HTTP Headers in PHP

Jan 28, 2014, by admin

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.