Understand Etags HTTP Header
I am using a caching library that has the function seen below. It is attempting to grab eTags from the Request on the 5th line but the eTags are never set.
When would a REQUEST have eTags? and how might you set them?
Thanks.
public function isNotModified(Request $request)
{
$lastModified = $request->headers->get('If-Modified-Since');
$notModified = false;
if ($etags = $request->getEtags()) {
$notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastM开发者_开发技巧odified);
} elseif ($lastModified) {
$notModified = $lastModified == $this->headers->get('Last-Modified');
}
if ($notModified) {
$this->setNotModified();
}
return $notModified;
}
The ETag header field is for responses only:
The ETag response-header field provides the current value of the entity tag for the requested variant.
But the getEtags
method could be the tags from the If-None-Match header field:
If any of the entity tags match the entity tag of the entity that would have been returned in the response to a similar GET request (without the If-None-Match header) on that resource, or if "
*
" is given and any current entity exists for that resource, then the server MUST NOT perform the requested method, unless required to do so because the resource's modification date fails to match that supplied in an If-Modified-Since header field in the request. Instead, if the request method was GET or HEAD, the server SHOULD respond with a 304 (Not Modified) response, including the cache- related header fields (particularly ETag) of one of the entities that matched. For all other request methods, the server MUST respond with a status of 412 (Precondition Failed).
This seems to match the given code exactly (I rearranged the first sentence to fit the code):
// the server MUST NOT perform the requested method
$notModified = (
// if any of the entity tags match the entity tag of the entity that
// would have been returned in the response to a similar GET request
// (without the If-None-Match header) on that resource
in_array($this->getEtag(), $etags)
// or if "*" is given and any current entity exists for that resource
|| in_array('*', $etags))
// unless required to do so because the resource's modification
// date fails to match that supplied in an If-Modified-Since header
// field in the request.
&& (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
The last expression (!$lastModified || $this->headers->get('Last-Modified') == $lastModified)
is equivalent to !($lastModified && $this->headers->get('Last-Modified') != $lastModified)
that fits the last sentence part better.
精彩评论