发一个修改过的缓存静态页面的类,包括实例示例。
时间:2010-07-15 来源:xhq6632
<?php /* * File name:htmlCache.php * modified by:xuhongquan * Contact:[email protected] * Last modified:2010-7-14 * * This file does the following things: * -在原来缓存的基本上作了一些修改 * -保证一定能够缓存成功 * -这个原本是网上找的一段代码,没有发现出处。修改了一些。重新发出来,供大家使用。 * -在原程序的基础上增加程序的灵活性。修改一些BUG * -不需要任何设置即可 */ header("Content-type: text/html; charset=utf-8"); ob_start(); class HtmlCache{ var $content = ""; var $pre = "<?php if(!defined('IN_DISCUZ')) exit('Access Denied');\n?>"; var $path = "cache"; var $time = 120; var $type = "abcdefg"; var $fileName = ""; var $sfileName = ""; var $url = ""; var $basepath = ""; //构造函数 function ArrCache($path =null,$time =null ,$type =null){ $this->path = ($path==null||$path=='')?$this->path:$path; $this->time = ($time==null||$time=='')?$this->time:$time; $this->fileType = ($type==null||$type=='')?$this->type:$type; $this->getFile(); $this->basepath=$_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.$this->path.DIRECTORY_SEPARATOR; $this->fileName =$this->basepath.md5($this->url).'.'.$this->fileType; $this->sfileName =$this->basepath.$this->url.'.'.$this->fileType; if (file_exists($this->fileName) && ((filemtime($this->fileName)+$this->time) > time())) { $fp = fopen($this->fileName,"r"); $this->content=rawurldecode(fread($fp,filesize($this->fileName))); fclose($fp); ob_end_flush(); return $this->content; } } function getFile($url=null){//取对应的url文件 if($url==null||$url==''){ $port=$_SERVER['SERVER_PORT']==80?'':':'.$_SERVER['SERVER_PORT']; $this->url='http://'.$_SERVER['SERVER_NAME'].$port.$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING']; }else{ $this->url=$url; } } // end func function endCache() { $data=ob_get_contents(); $data=rawurlencode($data); $this->writefile($this->fileName, $data); ob_end_flush(); } function writefile($file, $str) { if(empty($str)) return false; $path=pathinfo($file); if($path['dirname']) { $this->mkdirs($path['dirname']); } $fp = fopen($file, 'wb+'); if ($fp) { fwrite($fp, $str); fclose($fp); return true; } else { return false; } } function mkdirs($dir, $mode = 0777){ if (!is_dir($dir)) { $this->mkdirs(dirname($dir), $mode); return mkdir($dir, $mode); } return true; } }//end class ?>
用法示例
/* * File name:testHtml.php * Create by:xuhongquan * Contact:[email protected] * Last modified:2010-7-14 * * This file does the following things: * -这个文档是对缓存用法示例 * */ header("Content-type: text/html; charset=utf-8"); require_once('htmlCache.php'); $cache = new HtmlCache('cache/html'); $con=$cache->content; if(!empty($con)){ echo $con;//直接输出原来缓存的内容。 }else{ /* 这部分原就是你原来的流程,比方,你原来是查询输出之类。 这个函数就相当于把结果页面缓存起来,下次用户访问的时间好用。 */ $cache->endCache(); } ?>
修改天有空了,再完善一下。作一个缓存数据库的。
相关阅读 更多 +