PHP一个小巧的缓存类

功能很简单,就是缓存整个页面,可以设定缓存时间,可以缓存特定的URL,例如:test.php?id=12,当目标文件更新时,如test.php,缓存文件也会更新,即使仍处于缓存期内。

PHP代码
  1. class cache   
  2. {   
  3.     var $cache_dir = ‘./cache/’;//This is the directory where the cache files will be stored;   
  4.     var $cache_time = 120;//How much time will keep the cache files in seconds.   
  5.     
  6.     var $caching = false;   
  7.     var $file = ”;   
  8.     
  9.     function cache()   
  10.     {   
  11.     //Constructor of the class   
  12.     $this->file = $this->cache_dir . urlencode( $_SERVER[‘REQUEST_URI’] );   
  13.     if(file_exists($this->file)) $expired = $this->check_expire();   
  14.     else $expired = false;   
  15.     if ( file_exists ( $this->file ) && ( filemtime ( $this->file ) + $this->cache_time ) > time() && !$expired )   
  16.     {   
  17.         //Grab the cache:   
  18.         $handle = fopen$this->file , "r");   
  19.         do {   
  20.         $data = fread($handle, 8192);   
  21.         if (strlen($data) == 0) {   
  22.             break;   
  23.         }   
  24.         echo $data;   
  25.         } while (true);   
  26.         fclose($handle);   
  27.         exit();   
  28.     }   
  29.     else  
  30.     {   
  31.         //create cache :   
  32.         $this->caching = true;   
  33.         ob_start();   
  34.         $now = time();   
  35.         echo "<!–last modified:".$now."–>\n";   
  36.     }   
  37.     }   
  38.     
  39.     function close()   
  40.     {   
  41.     //You should have this at the end of each page   
  42.     if ( $this->caching )   
  43.     {   
  44.         //You were caching the contents so display them, and write the cache file   
  45.         $data = ob_get_clean();   
  46.         echo $data;   
  47.         $fp = fopen$this->file , ‘w’ );   
  48.         fwrite ( $fp , $data );   
  49.         fclose ( $fp );   
  50.     }   
  51.     }   
  52.     function check_expire(){   
  53.     $fp = fopen($this->file,"r");   
  54.     preg_match("/\:([\d]+)\-/",fread($fp,200),$time);   
  55.     $modify_time = $time[1];   
  56.     if($modify_time<filemtime($_SERVER[‘SCRIPT_FILENAME’])){   
  57.         return true;   
  58.     }   
  59.     else{   
  60.         return false;   
  61.     }   
  62.     
  63.     }   
  64. }  

用法:

PHP代码
  1. //Example :   
  2. $ch = new cache();   
  3. echo date("D M j G:i:s T Y");   
  4. $ch->close();  

Tags: 缓存

« 上一篇 | 下一篇 »

只显示10条记录相关文章

php禁止浏览器使用缓存页面 (浏览: 766, 评论: 1)
通过php缓存你的页面 (浏览: 819, 评论: 0)
加快php程序的输出 (浏览: 1134, 评论: 0)
使用application提高ASP数据显示效率 (浏览: 1251, 评论: 0)

Trackbacks

点击获得Trackback地址,Encode: UTF-8 点击获得Trackback地址,Encode: GB2312 or GBK 点击获得Trackback地址,Encode: BIG5

发表评论

评论内容 (必填):