php header()函数设置页面Cache缓存

2018-10-10 14:29:01

header()函数在php的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使用header前必须注意,在它之前不能任何输出,包括空格。

手册上,我们对于cache都是写着如何设置,以便让代码不被cache:

1
2
3
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // Date in the past

 

 

而且在设置的时候还得注意在header前不能有输出,否则header设置无效,但都没有写过,如何给页面设置Cache,虽然我们知道有一些办法,比如 E-TAG之类的。当然也有简单的设置:

比如我们在输出前,对内容进行md5,将它当成e-tag只要没变化,就不会有影响。也有其他的方式:

1
2
3
4
$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");

 

缓存1小时,主要是过期时间得用gmdate来设置,而不是date,这个要注意,其他都差不多。maxage要和expire能够对得上。

对于PHP产生的动态内容,只需要在内容输出之前输出强制缓存的header即可,比如下面的代码即要求浏览器缓存文件1个月:

1
2
3
4
5
6
7
8
<?php
  header("Cache-Control: public");
  header("Pragma: cache");
 
  $offset = 30*60*60*24; // cache 1 month
  $ExpStr "Expires: ".gmdate("D, d M Y H:i:s", time() + $offset)." GMT";
  header($ExpStr);
?>

 

对于静态文件,一般的服务器都支持第3级缓存状态。要想达到第四级的缓存效果,要么像之前GZIP压缩那样,用PHP外包一层,然后用PHP处理。要么需 要服务器端的支持,APACHE的一个模块mod_expires支持给文件添加expires header。把下面的代码加入你的blog目录下的.htaccess文件,如果你的服务器安装了mod_expires模块,则将自动生效,图片等强 制缓存一个月,html文档缓存10分钟。如果该模块没有安装,也不会出错。

1
2
3
4
5
6
7
8
9
10
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/png A2592000
ExpiresByType application/x-shockwave-flash A2592000
ExpiresByType text/css A2592000
ExpiresByType application/x-javascript A2592000
ExpiresByType text/html A600
</IfModule>

 在这里有mod_expires更详细的文档和教程。不过我要说明的是,mod_expires在绝大多数服务器上都没安装

  • 2023-09-21 16:49:06

    用webpack.ProvidePlugin来解决Photo-Sphere-Viewer旧版本浏览器兼容问题

    上篇文章已经搭建了最基本的项目,我用手机下载了一个版本62.点开头的chrome apk来测试。 果真白屏,啥也没有,也看不到报错信息。 赶紧安装 vconsole ,重启,刷新,依然白屏,连vconsole也没有。这可咋弄。 想了下,这浏览器老的是可以呀,还得修改编译参数,加大es5的处理。 根目录有一个配置文件 .browserslistrc 里面的配置如下