PHP快取頁面面函數。
/*****************************************************************
-- 函數名:cache_page(包括cache_page_go)
-- 作 用:輕鬆快速緩衝全站
-- 參 數:緩衝時間(單位:秒)
-- 傳回值:輸出內容
-- 實 例:cache_page(300); 函數使用在頁面的最上方
*******************************************************************/
function cache_page($refresh=20){
ob_start();//開啟緩衝區
$temp=sha1($_SERVER['PHP_SELF'].'|G|'.serialize($_GET).'|P|'.serialize($_POST));//快取檔案名字
$temp=dirname(__FILE__).'/cache/'.$temp;//快取檔案路徑
if(!file_exists($temp)){//快取檔案不存在
register_shutdown_function('cache_page_go',$temp);
}else{//快取檔案存在
if((time()-filemtime($temp))>$refresh ){//緩衝逾時
register_shutdown_function('cache_page_go',$temp);//調用函數
}else{//正常使用快取檔案
$temp=file_get_contents($temp);//取出快取檔案內容
echo $temp;//輸出緩衝內容
$temp=ob_get_contents();//取出緩衝區內容
ob_get_clean(); //清空緩衝區
echo $temp; //輸出
unset($temp,$refresh);/*登出變數*/
exit();
}
}
}
function cache_page_go($file){
$output=ob_get_contents();//擷取緩衝區內容
ob_get_clean(); //清空緩衝區
file_put_contents($file,$output,LOCK_EX);//寫入快取檔案
echo $output;//輸出緩衝內容
unset($output,$file);/*登出變數*/
exit();
}
建議將該函數放置在頁面的最開始處