3 回答
TA贡献1796条经验 获得超4个赞
您可能要使用private_no_expire而不是private,但是为您知道不会更改的内容设置一个较长的到期时间,并确保您处理if-modified-since和if-none-match请求的内容类似于Emil的帖子。
$tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
$etag = $language . $timestamp;
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false;
if ((($if_none_match && $if_none_match == $etag) || (!$if_none_match)) &&
($if_modified_since && $if_modified_since == $tsstring))
{
header('HTTP/1.1 304 Not Modified');
exit();
}
else
{
header("Last-Modified: $tsstring");
header("ETag: \"{$etag}\"");
}
$etag根据内容或用户ID,语言和时间戳记的校验和可能在哪里,例如
$etag = md5($language . $timestamp);
TA贡献1789条经验 获得超8个赞
这是一个为您执行http缓存的小类。它有一个名为“ Init”的静态函数,它需要2个参数,该页面(或浏览器请求的任何其他文件)的最后修改日期的时间戳,以及该页面可以保留的最大期限(以秒为单位)。浏览器缓存。
class HttpCache
{
public static function Init($lastModifiedTimestamp, $maxAge)
{
if (self::IsModifiedSince($lastModifiedTimestamp))
{
self::SetLastModifiedHeader($lastModifiedTimestamp, $maxAge);
}
else
{
self::SetNotModifiedHeader($maxAge);
}
}
private static function IsModifiedSince($lastModifiedTimestamp)
{
$allHeaders = getallheaders();
if (array_key_exists("If-Modified-Since", $allHeaders))
{
$gmtSinceDate = $allHeaders["If-Modified-Since"];
$sinceTimestamp = strtotime($gmtSinceDate);
// Can the browser get it from the cache?
if ($sinceTimestamp != false && $lastModifiedTimestamp <= $sinceTimestamp)
{
return false;
}
}
return true;
}
private static function SetNotModifiedHeader($maxAge)
{
// Set headers
header("HTTP/1.1 304 Not Modified", true);
header("Cache-Control: public, max-age=$maxAge", true);
die();
}
private static function SetLastModifiedHeader($lastModifiedTimestamp, $maxAge)
{
// Fetching the last modified time of the XML file
$date = gmdate("D, j M Y H:i:s", $lastModifiedTimestamp)." GMT";
// Set headers
header("HTTP/1.1 200 OK", true);
header("Cache-Control: public, max-age=$maxAge", true);
header("Last-Modified: $date", true);
}
}
- 3 回答
- 0 关注
- 445 浏览
添加回答
举报