Created
December 8, 2011 13:50
-
-
Save firegate666/1447045 to your computer and use it in GitHub Desktop.
Calculate etag and last-modified for given file and send not-modified since header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* class for cache control | |
*/ | |
final class CacheControl | |
{ | |
private function __construct() | |
{ | |
// no instances | |
} | |
/** | |
* calculate etag for filename and params | |
* | |
* @param String $filename | |
* @param array $params relevant request parameters for etag calculation | |
* @return String | |
*/ | |
static function etag($filename, $params = array()) | |
{ | |
$etag = fileinode($filename).'-'.filemtime($filename).'-'.filesize($filename); | |
$params = var_export($params, true); | |
return '"'.md5($etag.$params).'"'; | |
} | |
/** | |
* calculate last modified for filename | |
* | |
* @param String $filename | |
* @return String | |
*/ | |
static function last_modified($filename) | |
{ | |
return date('r', filemtime($filename)); | |
} | |
/** | |
* test if filename is not modified since | |
* | |
* @param String $filename | |
* @param array $params | |
* @param boolean $send_header if true send Last-Modified and Etag headers | |
* @return boolean | |
*/ | |
static function is_not_modified_since_file($filename, $params = array(), $send_header = true) | |
{ | |
$etag = self::etag($filename, $params); | |
$last_modified = self::last_modified($filename); | |
if ($send_header) | |
{ | |
header("Last-Modified: $last_modified", true); | |
header("Etag: $etag", true); | |
} | |
return self::is_not_modified_since($etag, $last_modified); | |
} | |
/** | |
* test if modified since | |
* | |
* @global $_SERVER['HTTP_IF_MODIFIED_SINCE'] | |
* @global $_SERVER['HTTP_IF_NONE_MATCH'] | |
* | |
* @param String $etag | |
* @param String $last_modified | |
* @return boolean | |
*/ | |
static function is_not_modified_since($etag, $last_modified) | |
{ | |
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? | |
stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : | |
false; | |
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? | |
stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : | |
false; | |
if ($if_none_match && $if_none_match == $etag && $if_modified_since && $if_modified_since == $last_modified) | |
{ | |
return true; | |
} | |
return false; | |
} | |
/** | |
* send 304 and exit() | |
*/ | |
static function send_not_modified_since() | |
{ | |
header('HTTP/1.0 304 Not Modified'); | |
exit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment