php文件缓存实例代码
缓存在实际使用当中应用很广泛,可以减轻对服务器数据库教程的访问,提高运行速度,目前很多cms内容管理系统中频繁使用缓存机制来提高系统运行的效率.
cache.php代码如下:
- <?php
-
-
-
-
-
-
-
- class cache {
-
- var $cachefile;
- var $cachefilevar;
-
- function cache() {
-
-
- $s=array(".","/");$r=array("_","");
- $this->cachefilevar=str_replace($s,$r,$_server["script_name"])."_".$_get[_actionvar_];
- $this->cachefile=$this->cachefilevar.".".md5($_server["request_uri"]);
- }
-
-
- function delete() {
-
- $d = dir(_cachepath_);
- $strlen=strlen($this->cachefilevar);
-
- while (false !== ($entry = $d->read())) {
- if (substr($entry,0,$strlen)==$this->cachefilevar) {
- if (!unlink(_cachepath_."/".$entry)) {echo "cache目录无法写入";exit;}
- }
- }
- }
-
-
- function check() {
-
- if (_recachetime_+0>0) {
-
- $var=@file(_cachepath_."/".$this->cachefilevar);$var=$var[0];
-
- if (time()-$var>_recachetime_) {
- $this->delete();$ischage=true;
- }
- }
-
- $file=_cachepath_."/".$this->cachefile;
-
- return (file_exists($file) and _cacheenable_ and !$ischange);
- }
-
-
- function read() {
-
- $file=_cachepath_."/".$this->cachefile;
-
- if (_cacheenable_) return readfile($file);
- else return false;
- }
-
-
- function write($output) {
-
- $file=_cachepath_."/".$this->cachefile;
-
- if (_cacheenable_) {
-
- $fp=@fopen($file,'w');
- if (!@fputs($fp,$output)) {echo "模板cache写入失败";exit;}
- @fclose($fp);
-
- if (_recachetime_+0>0) {
-
- $file=_cachepath_."/".$this->cachefilevar;
- $fp=@fopen($file,'w');
- if (!@fwrite($fp,time())) {echo "cache目录无法写入";exit;}
- @fclose($fp);
- }
- }
- }
-
- }
- ?>
使用过程,php代码如下:
- <?php
- define("_cachepath_","./cache/");
- define("_cacheenable_","1");
- define("_recachetime_","43200");
- include('cache.php');
- $cache=new cache();
- if ($cache->check()) {
- $template=$cache->read();
- }else {
- ob_start();
- ob_implicit_flush(0);
- ?>
-
- <?php
- $template = ob_get_contents();
- $cache->write($template);
- }
- ?>