header()函数在php的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使用header前必须注意,在它以前不能任何输出,包括空格。javascript
手册上,咱们对于cache都是写着如何设置,以便让代码不被cache:php
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之类的。固然也有简单的设置:css
好比咱们在输出前,对内容进行md5,将它当成e-tag只要没变化,就不会有影响。也有其余的方式:html
$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可以对得上。java
对于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 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在绝大多数服务器上都没安装服务器