1.如何阻止浏览器缓存页面
有两种方法,第一种是使用Html Meta标签,第二种是使用HTTP头
例子:
- <meta http-equiv='expires' content='mon,26 jul 1997 05:00:00 GMT'/>
- <meta http-equiv='pragma' content='no-cache'/>
传递到expires meta标签的日期告诉浏览器,缓存页面的拷贝总是过期的,遇到此标签后,浏览器通常不会缓存页面,
例子:
- <?php
- header('Ecpires:mon,26 jul 1997 05:00:00 GMT')
- header('pragma:no-cache');
- ?>
可以更进一步,使用由可使用HTTP/1.1 的浏览器所支持的cache-control头
- <?php
- header('Ecpires:mon,26 jul 1997 05:00:00 GMT');
- header('cache-control:no-store,no-cache,must-revalidate');
- header('cache-control:post-check()=0,pre-check()=0',false);
- header('pragma:no-cache');
- ?>
2.如何控制客户端的缓存
为了控制客户端缓存,有两个可供选择的方案,课设置页面的过期时间,或者对浏览器的请求头做出反应
1.设置一个页面过期头
- <?php
- function setexpires($expires){
- header('Expries:'.gmdate('D,d M Y H:i:s',time()+$expires).'GMT');
- }
- setexpries(10);
- echo ('this is page will destruct in 10 ');
- echo gmdate("H:i:s");
- echo ('<a href="'.$_SERVER['PHP_SELF'].'">view again</a>');
- ?>
3.按照浏览器的请求头行动
更为有效地客户端缓存控制方法是利用last-modified和if-modified-since头
这两个可用于HTTP1.0 这种行为技术上称为执行一个有条件的get请求,脚本是否返回内容取决于传入的if-modified-since请求头的值
例子:
<?php
$file='ifmodified.txt';
$random=array(0,1,1);
shuffle($random);
if($random[0]==0){
$fp=fopen($file.'w');
fwrite($fp,'x');
fclose($fp);
}
$lastmodified=filemtime($file);
header('Last-modified:'.gmdate('D, d M Y H:i:s',$lastmodified).'GMT');
$request=getallheaders();
if(isset($request['IF-Modified-Since'])){
$modifiedsince=explode(";",$request['IF-Modified-Since']);
$modifiedsince=strtotime($modifiedsince[0]);
}else{
$modifiedsince=0;
}
if
?>
4.如何将输出缓冲用于服务端缓存
在将其发送到浏览器之前,要捕获完成的页面并将其存贮到某个地方,例如存储大片一个文件中等到下一次执行此页面时,php脚本首先检查是否存在此页面的缓存版本,如果存在就直接向浏览器发送缓存
在此我们将关注php的内置缓存机制:输出缓冲器
例子:<?php
ob_start();
echo "a";
$content=ob_get_contents();
ob_end_clean();
echo "g";
echo $content;
?>
5.如何只缓存页面中的不常改变的部件
输出控制函数能够以调整内容生存期的方式来提升站点性能
输出缓冲可以将页面的几部分分别缓存到几个文件中,接下来可从这些文件中重建页面输出
例子:
<?php
function writecache($contents,$filename){
$fp=fopen('./cache/'.$filename,'w');
fwrite($fp,$contents);
fclose($fp);
}
function readcache($filename,$expries){
if(file_exists('./cache/'.$filename)){
if((time()-$expries) > filemtime('./cache/'.$filename)){
return false;
}
$cache=file('./cache/'.$filename);
return implode('',$cache);
}
return false;
}
ob_start();
if(!$header=readcache('header.cache',3333)){
?>
<head>
<title>cache</title>
</head>
<body>
<p>this is a cache file</p>
<?php echo 'header time is '.date('H:i:s') ?>
<?php
$header=ob_get_contents();
writecache($header,'header.cache');
ob_clean();
}
if(!$body=readcache('body.cache',4)){
echo 'now time is '.date('H:i:s')."<br>";
$body=ob_get_contents();
ob_clean();
writecache($body,'body.cache');
}
if(!$foot=readcache('foot.cache',444)){
?>
<p>foot time is "<?php echo date('H:i:s'); ?></p>
</body>
<?php
$foot=ob_get_contents();
ob_clean();
writecache($foot,'foot.cache');
}
ob_end_clean();
echo $header.$body.$foot;
?>
我的浅显理解就是把固定的页面部分保存为一个文件,相当于引用,这样做的好处是 减少 服务器的压力