Skip to content

Commit

Permalink
Added cache headers for .html files
Browse files Browse the repository at this point in the history
"This code snippet checks if a page has been modified since it was last displayed. If so, it sends a "304 not modified" header and exits, otherwise the content is rendered." source: http://css-tricks.com/snippets/php/intelligent-php-cache-control/

Adds Last-Modified, Etag (using md5; performance is still good for files under 1MB), and Cache-Control header.
  • Loading branch information
kevcenteno committed Oct 4, 2013
1 parent 9b8e479 commit e2f4698
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion main.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,24 @@ function skipCache() {
$file = implode('/', array_map('rawurlencode', explode('/', $file)));
// Find file by extension (either *.html or *.php)
if (file_exists($cacheBaseDir . $cacheDir . $file . '.html')) {
//source: http://css-tricks.com/snippets/php/intelligent-php-cache-control/
$filepath = $cacheBaseDir . $cacheDir . $file . '.html';
$lastModified=filemtime($filepath);
$etagFile = md5_file($filepath);
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);

header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
header("Etag: $etagFile");
header('Cache-Control: public');
header('X-SilverStripe-Cache: hit at '.@date('r'));
echo file_get_contents($cacheBaseDir . $cacheDir . $file . '.html');

if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile) {
header("HTTP/1.1 304 Not Modified");
exit;
}

echo file_get_contents($filepath);
if ($cacheDebug) {
echo "<h1>File was cached</h1>";
}
Expand Down

0 comments on commit e2f4698

Please sign in to comment.