使PHP页面返回“304 Not Modified"如果它没有被修改 [英] Make PHP page return "304 Not Modified" if it hasn't been modified

查看:32
本文介绍了使PHP页面返回“304 Not Modified"如果它没有被修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP 文件,它每次都会返回相同的内容并使用相同的 $_GET 参数——这是确定性的.

I have a PHP file that will return the same thing with the same $_GET parameters every time -- it's deterministic.

不幸的是,为了提高效率(经常请求此文件),每当请求 PHP 页面时,Apache 默认为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 Not Modified 标头当且仅当参数相同?

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;
?>

所有常见的陷阱都适用:您可能无法为登录用户显示缓存页面,缓存部分内容可能更可取,您自己负责防止缓存中的陈旧内容(可能在后端或数据库中使用触发器)修改,或者只是玩弄 getUrlEtag 逻辑),等等.

All common pitfalls apply: you can possibly not display cache pages for logged in users, a caching of partial content could be more desirable, you are yourself responsible for preventing stale content in the cache (possibly using triggers in backend or database on modifications, or just playing around with the getUrlEtag logic), etc. etc.

如果 HTTP_IF_MODIFIED_SINCE 更容易控制,您也可以尝试一下.

You could also play around with HTTP_IF_MODIFIED_SINCE if that's easier to control.

这篇关于使PHP页面返回“304 Not Modified"如果它没有被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆