使PHP页面返回" 304未修改"如果它没有被修改 [英] Make PHP page return "304 Not Modified" if it hasn't been modified
问题描述
我有一个PHP文件,将每次返回同样的事情在同一$ _GET参数 - 这是确定的。
I have a PHP file that will return the same thing with the same $_GET parameters every time -- it's deterministic.
不幸的是,效率(请求该文件很多时候),Apache的默认每次请求PHP页面200 OK响应,让用户重新下载该文件。
Unfortunately for efficiency (this file is requested very often), Apache defaults to a "200 OK" response whenever a PHP page is requested, making the user download the file again.
有没有什么办法来发送 304未修改
头的当且仅当的参数是一样的吗?
Is there any way to send a 304 Not Modified
header if and only if the parameters are the same?
奖金:
我可以设置它的到期时间,因此,如果缓存的页面比说,老三天以上,它发送一个200 OK的反应?
Bonus: Can I set an expiry time on it, so that if the cached page is more than, say, three days old, it sends a "200 OK" response?
推荐答案
没有缓存的网页自己(或至少其Etag的)你不能真正利用304的全功能的缓存算法有点超出范围的,但总体思路:
Without caching the page yourself (or at least its Etag) you cannot really make use of the 304. A full fledged caching algorithm is somewhat out of scope, but the general idea:
<?php
function getUrlEtag($url){
//some logic to get an etag, possibly stored in memcached / database / file etc.
}
function setUrlEtag($url,$etag){
//some logic to get an etag, possibly stored in memcached / database / file etc.
}
function getPageCache($url,$etag=''){
//[optional]some logic to get the page from cache instead, possibly not even using etag
}
function setPageCache($url,$content,$etag=''){
//[optional]some logic to save the page to cache, possibly not even using etag
}
ob_start();
$etag = getUrlEtag($_SERVER['REQUEST_URI']);
if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
if(($content=getPageCache($_SERVER['REQUEST_URI'],$etag))!==false){
echo $content;
exit;
}
?>
//the actual page
<?php
$content = ob_get_clean();
setUrlEtag($_SERVER['REQUEST_URI'],$etag=md5($url.$content));
function setPageCache($_SERVER['REQUEST_URI'],$content,$etag);
header("Etag: $etag");
echo $content;
?>
所有常见的陷阱适用:你都不可能不登录的用户,部分内容缓存可能是更理想的显示缓存页面,你是你自己负责缓存preventing陈旧的内容(可能使用在后台触发或数据库的修改,或者只是玩弄的 getUrlEtag
逻辑),等等等等。
您也可以玩弄 HTTP_IF_MODIFIED_SINCE
如果这是更容易控制。
You could also play around with HTTP_IF_MODIFIED_SINCE
if that's easier to control.
这篇关于使PHP页面返回&QUOT; 304未修改&QUOT;如果它没有被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!