From e2f4698402603d653e2f58038cf934239dc6fb94 Mon Sep 17 00:00:00 2001 From: Kevin Centeno Date: Fri, 4 Oct 2013 15:47:36 -0400 Subject: [PATCH] Added cache headers for .html files "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. --- main.php | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/main.php b/main.php index 5540df1..e62f569 100644 --- a/main.php +++ b/main.php @@ -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 "

File was cached

"; }