强制浏览器缓存 .php 文件

3
我需要浏览器缓存一个大型的,大部分静态的 .php 文件。我通过 ajax 打开它并想将其添加到当前页面。
经过一些研究,我找到了这个
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");

这在IE中有效,但在Chrome和Firefox中无效。
这是请求内容。
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Cache-Control   max-age=0
Connection  keep-alive
Content-Type    application/x-www-form-urlencoded
Cookie  PHPSESSID=5dkvr42f4it8pnnnqpesj6l413
Host    localhost
Referer http://localhost/mifa/Suche.php
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1
charset utf-8

这里是响应头部信息

Cache-Control   max-age=3600
Connection  Keep-Alive
Content-Type    text/html
Date    Thu, 05 Jul 2012 15:28:22 GMT
Expires Thu, 05 Jul 2012 16:28:22 GMT
Keep-Alive  timeout=5, max=91
Pragma  cache
Server  Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
Transfer-Encoding   chunked
X-Powered-By    PHP/5.3.8

我需要做出哪些改变?

编辑

显然,只有IE没有将Cache-Control max-age=0附加到请求中。

这是请求的JS函数:

url = "includes/Orte.php";
obj.onreadystatechange = rState;
obj.open("GET", url, true);
obj.setRequestHeader("Pragma", "");
obj.setRequestHeader("Cache-Control", "");
obj.setRequestHeader("charset", "utf-8");
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.setRequestHeader("Connection", "close");
obj.send();

function rState(){
    if(obj.readyState == 4){
        if (obj.status == 200){
            //alert("Response Text Ajax:\n" + obj.responseText + "\nEnd Response Text");
        }
    }
}

您可以通过在第二个连续请求时发送HTTP 304未修改来确保浏览器不再请求,从而实现此目的。我相信,尽管您设置了正确的缓存日期/时间等信息,但某些浏览器仍会再次请求文件。 - fdomig
2个回答

2

请求头中的Cache-Control: max-age=0表示您已要求浏览器刷新页面,因此它会忽略缓存。

为避免这种情况,请直接访问页面而不是点击刷新按钮(例如,聚焦地址栏并按回车键)。

此外,如果页面位于HTTPS URL上,则可能需要将public添加到Cache-Control头中,否则某些浏览器将无法缓存它。


你说得对,只有IE不会附加max-age=0。我该怎么解决?我已经在上面发布了JS代码。你知道ff和chrome在哪里插入该标头吗? - ellow7

0
两个想到的方法是使用最后修改头和使用.htaccess缓存控制。后者适用于广泛类型,但您也可以仅将其用于一个文件夹,并将该文件放在单独的文件夹中。
header("Last-Modified: ... ");

Last-Modified 会触发浏览器在下一次请求中发送 If-Modified-Since,脚本需要解析并可能回复一个 304 Not Modified 状态。这将防止浏览器下载整个内容,但不会阻止它发出请求。 - Arnaud Le Blanc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接