PHP Caching Headers
Posted March 22nd, 2010 in PHP
Yesterday I looked at how to control browser caching with Apache's mod_expires and today look at how to set the caching/expiry time with headers in PHP to either make sure the resulting data is never cached by the browser, or is cached for a set amount of time.
Make sure a page is never cached with PHP
To make sure the page is never cached (or whatever other dynamic content generated from PHP such as images, RSS files etc) add the following to the start of your script:
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: $ts");
header("Last-Modified: $ts");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
To set the amount of time to cache
If instead you want the output from the script to be cached for a certain amount of time, set the expires header to a time in the future. For example, to make it so the browser will cache the output for 1 hour do this:
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");
The Cache-Control header requires the number of seconds to cache the file so in this example it's 3600 because 60 seconds x 60 minutes = 3600.
Related posts:
- Using Apache mod_expires to control browser caching (Sunday, March 21st 2010)
- Setting 503 Service Temporarily Unavailable headers with Apache .htaccess (Sunday, March 14th 2010)
- Output buffering with PHP (Monday, December 21st 2009)
- Get the headers sent from the browser with PHP (Thursday, September 17th 2009)
- Image headers with PHP (Tuesday, July 22nd 2008)

Comments
blog comments powered by Disqus