php header()函数设置页面 Cache 缓存
header()函数在 php 的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使
用
header 前必须注意,在它之前不能任何输出,包括空格。
手册上,我们对于
cache 都是写着如何设置,以便让代码不被 cache:
代码如下
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 只要没变化,就不会有影响。也
有其他的方式:
代码如下
$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 个月:
代码如下
<?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 分钟。如果该模块没有安装,也不会出错。
代码如下
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000