程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP一個小巧的緩存類

PHP一個小巧的緩存類

編輯:關於PHP編程

功能很簡單,就是緩存整個頁面,可以設定緩存時間,可以緩存特定的URL,例如:test.php?id=12,當目標文件更新時,如test.php,緩存文件也會更新,即使仍處於緩存期內。

class cache
{
var $cache_dir = ./cache/;//This is the directory where the cache files will be stored;
var $cache_time = 120;//How much time will keep the cache files in seconds.

var $caching = false;
var $file = ;

function cache()
{
//Constructor of the class
$this->file = $this->cache_dir . urlencode( $_SERVER[REQUEST_URI] );
if(file_exists($this->file)) $expired = $this->check_expire();
else $expired = false;
if ( file_exists ( $this->file ) && ( filemtime ( $this->file ) + $this->cache_time ) > time() && !$expired )
{
//Grab the cache:
$handle = fopen( $this->file , "r");
do {
$data = fread($handle, 8192);
if (strlen($data) == 0) {
break;
}
echo $data;
} while (true);
fclose($handle);
exit();
}
else
{
//create cache :
$this->caching = true;
ob_start();
$now = time();
echo "<!--last modified:".$now."--> ";
}
}

function close()
{
//You should have this at the end of each page
if ( $this->caching )
{
//You were caching the contents so display them, and write the cache file
$data = ob_get_clean();
echo $data;
$fp = fopen( $this->file , w );
fwrite ( $fp , $data );
fclose ( $fp );
}
}
function check_expire(){
$fp = fopen($this->file,"r");
preg_match("/:([d]+)-/",fread($fp,200),$time);
$modify_time = $time[1];
if($modify_time<filemtime($_SERVER[SCRIPT_FILENAME])){
return true;
}
else{
return false;
}

}
}


用法:

//Example :
$ch = new cache();
echo date("D M j G:i:s T Y");
$ch->close();

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved