Tuesday 23 October 2012

[dcphp-dev] Caching via "304 not modified" messages

Awesome, I'd never thought of using Status Code Definitions to ease server load.


This clever bit of code checks if a page has been modified since it
was last displayed and if it hasn't, it sends a "304 not modified"
header and exits, otherwise the content is loads as normal. Add the
code below to the top of each PHP page you want to apply it to. It's
especially useful if you serve static content via php and want it to
be cached like ordinary HTML or CSS.


//get the last-modified-date of this very file
$lastModified=filemtime(__FILE__);
//get a hash of this file
$etagFile = md5_file(__FILE__);
//get the HTTP_IF_MODIFIED_SINCE header if set
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
$_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
//get the HTTP_IF_NONE_MATCH header if set
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);

//set last-modified header
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
//set etag-header
header("ETag: \"$etagFile\"");
//make sure caching is turned on
header('Cache-Control: public');

//check if page has changed If not send 304 header and exit
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified ||
$etagHeader == $etagFile)
{
header("HTTP/1.1 304 Not Modified");
exit;
}

echo "Page last modified: ".date("d.m.Y H:i:s",time());


source:http://papermashup.com/php-clever-caching/

--
You received this message because you are subscribed to the Google
Group: "Washington, DC PHP Developers Group" - http://www.dcphp.net
To post, send email to washington-dcphp-group@googlegroups.com
To unsubscribe, send email to washington-dcphp-group+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/washington-dcphp-group?hl=en

0 comments:

Post a Comment