session_cache_limiter('public'); //Cache on clients and proxies session_cache_expire(180); //3 hours header('Content-Type: ' . $documentMimeType . '; charset=' . $charset); header('ETag: "' . $eTag . '"'); //$eTag is a MD5 of $currentLanguage + $lastModified if ($isXML) header('Vary: Accept'); //$documentMimeType can be either application/xhtml+xml or text/html for XHTML (based on $_SERVER['HTTP_ACCEPT']) header('Last-Modified: ' . $lastModified); header('Content-Language: ' . $currentLanguage);
此外,每个页面都有自己的URL(适用于所有语言).例如,“index.PHP”将在英文URL“/ en / home”和法语“/ fr / accueil”下提供.
我最大的问题是回答“304 Not Modified”到if-none-match和if-modified-因为HTTP请求只在需要时.
我发现的最好的文档是:
http://rithiur.anthd.com/tutorials/conditionalget.php
这就是我所做的实现(这段代码在可以缓存的页面上称为ASAP):
$ifNoneMatch = array_key_exists('HTTP_IF_NONE_MATCH',$_SERVER) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false; $ifModifiedSince = array_key_exists('HTTP_IF_MODIFIED_SINCE',$_SERVER) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false; if ($ifNoneMatch !== false && $ifModifiedSince !== false) { //Both if-none-match and if-modified-since were received. //They must match the document values in order to send a HTTP 304 answer. if ($ifNoneMatch == $eTag && $ifModifiedSince == $lastModified) { header('Not Modified',true,304); exit(); } } else { //Only one header received,it it match the document value,send a HTTP 304 answer. if (($ifNoneMatch !== false && $ifNoneMatch == $eTag) || ($ifModifiedSince !== false && $ifModifiedSince == $lastModified)) { header('Not Modified',304); exit(); } }
我的问题有两个:
>这是正确的方法吗?我的意思是当if-none-match和if-modified-since被发送时,两者必须匹配才能回答304,如果只发送了两个中的一个,只匹配这个就可以发送304了吗?
>在这里描述的上下文中使用时,这2个片段是否对公共缓存友好(我的意思是代理和Web浏览器上的缓存友好)?
顺便说一句,我只使用PHP 5.1.0(我不支持低于此版本的版本).
编辑:添加赏金…我期待质量答案.如果你在猜什么,不要回答/投票!
>该解决方案是代理友好的,您可以使用Cache-control:proxy-revalidate强制缓存遵守您为其提供的有关资源的任何新鲜度信息(仅适用于共享代理缓存)
以下是可能有用的功能:
function isModified($mtime,$etag) { return !( ( isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mtime ) || ( isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag ) ) ; }
我建议您看看以下文章:http://www.peej.co.uk/articles/http-caching.html
更新:
[AlexV] Is is even possible to receive if-none-match AND if-modified-since at the same time?
你绝对可以同时设置.然而:
If none of the entity tags match,then the server MAY perform the requested method as if the If-None-Match header field did not exist,but MUST also ignore any If-Modified-Since header field(s) in the request. That is,if no entity tags match,then the server MUST NOT return a 304 (Not Modified) response.
07002
示例值(W代表’弱’;在RFC2616 #13.3.3中阅读更多内容):
If-None-Match: "xyzzy","r2d2xxxx","c3piozzzz" If-None-Match: W/"xyzzy",W/"r2d2xxxx",W/"c3piozzzz" If-Modified-Since: Sat,29 Oct 1994 19:43:31 GMT If-None-Match: *
作为特殊情况,值“*”匹配资源的任何当前实体.