php如何设置缓存时间

发布时间:2024-02-09 点击:133
在php中可以通过“header()”方法来设置页面cache缓存,其语法如“header("pragma: cache");$expstr = "expires: ".gmdate("d, d m y h:i:s", ),gmt";”。
推荐:《php视频教程》
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 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在绝大多数服务器上都没安装.

台湾免费云服务器租用
网站建设及价格是怎样的?网站建设的技巧有哪些?
网站建设建站流程是怎样的 网站建设怎么选域名
阿里云服务器怎么加ip
域名绑定服务器ip应该怎么操作?
如何创建网站?创建网站之前要做哪些准备工作
【淮北网站建设】百度指数是什么意思?而百度收录的差额金额
云服务器备案通过要多久才能用