PHP Cache Control for dynamic pages
http://ontosys.com/php/cache.html
PHP Cache Control
This note describes a scheme for allowing PHP pages to be cached by a browser.
Example files
cache_check.inc — Logic to support caching of dynamic pages
<?php
$if_modified_since = preg_replace('/;.*$/', '', $HTTP_IF_MODIFIED_SINCE);
$mtime = filemtime($SCRIPT_FILENAME);
$gmdate_mod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
if ($if_modified_since == $gmdate_mod) {
header("HTTP/1.0 304 Not Modified");
exit;
}
header("Last-Modified: $gmdate_mod");
?>
|
The value of the HTTP If-Modified-Since header (if any) is available in $HTTP_IF_MODIFIED_SINCE. We check the date value in that header against the modification date of the executed PHP script file itself. If they are the same, we send a 304 response and quit.
Otherwise, we send a Last-Modified header with the file’s modification date.
cachable.php3 — An example cacheable dynamically-generated file
<?php // -*- sgml-parent-document: ("dummy.html" "html" "body" ()) -*-
include 'cache_check.inc';
if (isset($touch)) touch($SCRIPT_FILENAME);
$gmdate_now = gmdate('D, d M Y H:i:s') . ' GMT';
$now = time();
print "
<table>
<tr><td>if_modified_since</td><td>$if_modified_since</td></tr>
<tr><td>gmdate_mod</td><td>$gmdate_mod</td></tr>
<tr><td>gmdate_now</td><td>$gmdate_now</td></tr>
</table>
<p>
<a href=\"$SCRIPT_NAME\">Link to self</a>.<br>
<a href=\"$SCRIPT_NAME?touch=y&time=$now\">Update source file</a>.<br>
<a href=\"$SCRIPT_NAME?time=$now\">Link to self with varying URL</a>.
";
?>
|
This dynamic page simply generates some output for testing purposes. Note that the gmdate_now value will not appear to change if the browser uses the file from its cache or if the server sends back a 304.