不同的網站所需要的緩存功能不一樣,有的網站只需要緩存所請求的get信息,但是有的網站卻需要緩存完整url的信息,這裏記錄一個常用到的緩存代碼,目前已經寫好了.
緩存代碼
<?php
//緩存存放目錄
define('CACHE_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'empirecms');
//緩存時間 單位秒
define('CACHE_TIME', 86400*7);
//緩存文件後綴
define('CACHE_FIX','.php');
date_default_timezone_set("Asia/Shanghai");
$CacheName=md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']) . CACHE_FIX; //緩存文件名
$CacheDir=CACHE_ROOT . DIRECTORY_SEPARATOR . substr($CacheName,0,1);//緩存文件存放目錄
$CacheUrl=$CacheDir . DIRECTORY_SEPARATOR . $CacheName;//緩存文件的完整路徑
//GET方式請求才緩存,POST之後一般都希望看到最新的結果
if($_SERVER['REQUEST_METHOD']!='POST'){
//如果緩存文件存在,並且沒有過期,就把它讀出來。
if(file_exists($CacheUrl) && time()-filemtime($CacheUrl)<CACHE_TIME){
echo gzuncompress(file_get_contents($CacheUrl));
exit;
}
//判斷文件夾是否存在,不存在則創建
elseif(!file_exists($CacheDir)){
if(!file_exists(CACHE_ROOT)){
mkdir(CACHE_ROOT,0777);
chmod(CACHE_ROOT,0777);
}
mkdir($CacheDir,0777);
chmod($CacheDir,0777);
}
//回調函數,當程序結束時自動調用此函數
function AutoCache($contents){
global $CacheUrl;
$fp=fopen($CacheUrl,'wb');
$contents = "<!--站長qq:1810216796 緩存更新時間: ".(date("Y-m-d H:i:s", time()))."-->\r\n".$contents;
fwrite($fp,gzcompress($contents));
fclose($fp);
chmod($CacheUrl,0777);
//生成新緩存的同時,自動刪除所有的老緩存,以節約空間,可忽略。
DelOldCache();
return $contents;
}
function DelOldCache(){
chdir(CACHE_ROOT);
foreach (glob("*/*".CACHE_FIX) as $file){
if(time()-filemtime($file)>CACHE_TIME) unlink($file);
}
}
ob_start('AutoCache');//回調函數 auto_cache
clearstatcache();//清除文件緩存
}else{
//不是GET的請求就刪除緩存文件。
if(file_exists($CacheUrl)) unlink($CacheUrl);
}
?>使用方法
使用的話,直接引用代碼即可
代碼重點
主要是php的回調函數不好理解,惡補一些基礎後,勉強可以理解,其中ob_start這個函數我去查了一下手冊,具體如下:
ob範例
用戶自定義回調函數的例子
<?php
function callback ( $buffer )
{
// replace all the apples with oranges
return ( str_replace ( "apples" , "oranges" , $buffer ));
}
ob_start ( "callback" );
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush ();
?>
以上例程會輸出:
<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>
