PHP缓存页面函数

 
更多

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

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

简单压缩后代码如下:

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();}
打赏

本文固定链接: https://www.cxy163.net/archives/4100 | 绝缘体

该日志由 绝缘体.. 于 2013年05月23日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: PHP缓存页面函数 | 绝缘体
关键字: , , , ,

PHP缓存页面函数:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter