当前位置:Gxlcms > PHP教程 > PHP缓存页面方法

PHP缓存页面方法

时间:2021-07-01 10:21:17 帮助过:5人阅读

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();

}

建议将该函数放置在页面的最开始处

人气教程排行