【问题标题】:Force the browser to cache a .php强制浏览器缓存一个 .php
【发布时间】:2023-04-01 02:28:02
【问题描述】:

我需要浏览器缓存一个大的、大部分是静态的 .php 文件。我通过ajax打开它并想将它添加到当前页面。

经过一番研究,如果找到this

$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 Not modified 来确保浏览器不再询问来实现此目的。我相信尽管您设置了正确的缓存日期/时间等,但某些浏览器确实会再次请求文件。

标签: php http-headers


【解决方案1】:

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

在不点击刷新的情况下访问页面(例如,聚焦地址栏并按回车键)以避免这种情况。

此外,如果页面位于 HTTPS URL 上,您可能必须将 public 添加到 Cache-Control 标头,否则某些浏览器不会缓存它。

【讨论】:

  • 你是对的,只有IE没有附加max-age=0。我该如何解决?我在上面贴了JS的代码。你知道 ff 和 chrome 在哪里插入那个标题吗?
【解决方案2】:

想到的两件事是最后修改的标头和使用 .htaccess 缓存控制。后者适用于广泛的类型,但您可以将其仅用于一个文件夹,而该文件本身位于一个文件夹中。

header("Last-Modified: ... ");

【讨论】:

  • Last-Modified 将触发浏览器在其下一个请求中发送If-Modified-Since;脚本必须对其进行解析,并可能以304 Not Modified 状态回复。这将阻止浏览器下载整个内容,但不会发出请求。
猜你喜欢
  • 1970-01-01
  • 2014-07-18
  • 2011-10-11
  • 2016-02-18
  • 1970-01-01
相关资源
最近更新 更多