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个月:
代码如下 复制代码
对于静态文件,一般的服务器都支持第3级缓存状态。要想达到第四级的缓存效果,要么像之前gzip压缩那样,用php外包一层,然后用php处理。要么需要服务器端的支持,apache的一个模块mod_expires支持给文件添加expires header。把下面的代码加入你的blog目录下的.htaccess文件,如果你的服务器安装了mod_expires模块,则将自动生效,图片等强制缓存一个月,html文档缓存10分钟。如果该模块没有安装,也不会出错。
代码如下 复制代码
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
在这里有mod_expires更详细的文档和教程。不过我要说明的是,mod_expires在绝大多数服务器上都没安装
http://www.bkjia.com/phpjc/631539.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/631539.htmltecharticleheader()函数在php的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使用header前必须注意,在它之前不能任何输出,包括空格。...