【发布时间】:2013-08-13 20:30:29
【问题描述】:
此 PHP 代码为 xml 文件生成一个 eTag。问题是 eTag 仅在其自身文件被更新/修改时才更新。当动态结果更新时,我也需要更新 etag。知道如何做到这一点吗?
//get the last-modified-date of this very file
$lastModified=filemtime(__FILE__);
//get a unique hash of this file (etag)
$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 (etag: unique file hash)
$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
//check if page has changed. If not, send 304 and exit
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile)
{
header("HTTP/1.1 304 Not Modified");
exit;
}
【问题讨论】:
-
获取动态内容的唯一哈希而不是文件,并将其设置为
eTag。喜欢$etagFile = md5( $your_output ); -
将其设置为一个唯一值,表示您的最后一次更新。可能是您数据中的一个简单的最后更新时间戳,但如果 1 秒内可能有多次更改,这有点容易受到攻击,在这种情况下,您需要添加最后一个内容的标识符。类似于伪代码
md5(md5file.max(mtimefile,mtimedata).identifierlastupdatedrecord); -
你能详细说明一下吗?我如何获得动态内容的唯一哈希? @bystwn22
-
@apak 看看我的回答,希望对你有帮助。
标签: php xml apache cache-control etag