PHP缓存类

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP缓存类脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 js-code.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

参数详解如下:

一个参数:
缓存二级目录
第二个参数:缓存时间  认1800
第三个参数:是否需要三级目录  0:不需要  1 需要  认0
第四个参数:缓存后缀  认 .htML
 
<?PHP
class PHP_cache{
  public function __construct($file_dir,$cache_time=1800,$file_two=0,$file_fix='.htm'){
	$this->cache_root=dirname(__FILE__).'/../cache';//缓存存放目录
	$this->file_dir=$file_dir;
	$this->cache_time=$cache_time;
	$this->file_two=$file_two;
	$this->file_fix=$file_fix;
	$this->file_name=md5($_SERVER['REQUEST_URI']).$this->file_fix;//缓存文件名
	$this->cache_file=$this->cache_dir=$this->cache_root.'/'.$this->file_dir;//缓存的二级文件夹
	if($this->file_two==1)$this->cache_dir=$this->cache_root.'/'.$this->file_dir.'/'.substr($this->file_name,2);//缓存的最终文件夹
	$this->cache_url=$this->cache_dir.'/'.$this->file_name;//文件存放的完整路径
	
	//GET方式请求才缓存,POST之后一般都希望看到最新的结果 
    if($_SERVER['REQUEST_METHOD']=='GET'){
      //如果缓存文件存在,并且没有过期,就把它读出来。
      if(file_exists($this->cache_url) && time()-filemtime($this->cache_url)<$this->cache_time){ 
        $fp=foPEn($this->cache_url,'rb'); 
        fpassthru($fp); 
        fclose($fp); 
        exIT; 
      }elseif(!file_exists($this->cache_dir)){//判断文件夹是否存在,不存在则创建
	    if(!file_exists($this->cache_file)){
		  if(!file_exists($this->cache_root)){
	        mkdir($this->cache_root,0777); 
            chmod($this->cache_root,0777);
		  }
		  mkdir($this->cache_file,0777); 
          chmod($this->cache_file,0777);
	   	  if($this->file_two==1){
            mkdir($this->cache_dir,0777); 
            chmod($this->cache_dir,0777);
		  }
	    }
	  }
	  //回调函数 AutoCache 
      //ob_start("AutoCache");
	  ob_start(array($this,"AutoCache"));
    }else{
	  //不是GET的请求就删除缓存文件 
      if(file_exists($this->cache_url))unlink($this->cache_url);
    }
  }
  function AutoCache($contents){
    $fp=fopen($this->cache_url,'wb'); 
    fwrite($fp,$contents); 
    fclose($fp); 
    chmod($this->cache_url,0777); 
    //生成新缓存的同时,自动删除所有的老缓存,以节约空间,可忽略。 
    $this->DeLOLdCache();
    return $contents;
  }
  function DelOldCache(){
    chdir($this->cache_root); 
    foreach (glob("*/*".$this->file_fix) as $file){ 
      if(time()-filemtime($file)>$this->cache_time)unlink($file);
    }
  }
}
?>

脚本宝典总结

以上是脚本宝典为你收集整理的PHP缓存类全部内容,希望文章能够帮你解决PHP缓存类所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:PHP缓存类