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:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    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.