Home / PHP Caching Headers

PHP Caching Headers

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.