PHP緩存類
參數詳解如下:
第一個參數:緩存二級目錄
第二個參數:緩存時間 默認1800
第三個參數:是否需要三級目錄 0:不需要 1 需要 默認0
第四個參數:緩存后綴 默認 .html
第一個參數:緩存二級目錄
第二個參數:緩存時間 默認1800
第三個參數:是否需要三級目錄 0:不需要 1 需要 默認0
第四個參數:緩存后綴 默認 .html
調用方法:
$cache = new php_cache('index');
$cache = new php_cache('index',1800);
$cache = new php_cache('index',1800,1);
$cache = new php_cache('index',1800,1,'.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,0,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);
}
}
}
?>
</pre>
本文由用戶 lpki123 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!