用ob_start()控制缓冲,给页面做文件缓存,加速页面

我们可能都有这样的经验,用php写了一个打开好几个数据库,几十次数据查询的首页,速度慢是可想而知啊,但是这个页面不大好做模板生成静态页,太麻烦了。怎么办了?我使用了这个解决方案,控制php的输出缓冲,截获处理后的html,保存成文件,然后的请求就检查这个文件的时间,若在设置的时间内,直接读取,发送。如果已经超时,就重新读取动态页面。

<? php
// --------------------------------------------------------------------------
//文件名:index.php
//描述:主站首页
//需求:PHP4(http://www.php.net)

//Copyright(C),www.cnfdc.com.cn,2005,AllRightsReserved.

//作者:lonestone(wangyong.yichang@gmail.com)

//--------------------------------------------------------------------------
//缓存文件名和缓存时间

$cachefilename = ' ./cache/index.cache ' ;
$cachetime = 3600 ;

// 强制更新缓存
if ( $_GET [ ' c ' ])
{
echo CacheFile();
die ();
}

// 检测缓存是否存在
if ( file_exists ( $cachefilename ))
{
$lastmodifytime = filemtime ( $cachefilename );
if ( $lastmodifytime && ( time () - $lastmodifytime ) > $cachetime )
{
echo CacheFile();
}
else
{
echo ReadCache();
}
}
else
{
echo CacheFile();
}


// 生成HTML并缓存成文件
function CacheFile()
{
global $cachefilename ;
// 打开输出缓存
ob_start ();

// 这里开始链接数据库,查询,用ADODB+SMARTY技术。

$tpl -> Display( " index.html " );
// 处理完成,截获缓冲内容


//得到缓存内容

$content = ob_get_contents ();
// 清空缓冲区,否则最终还是会输出给浏览器,这样就会有两个首页了
ob_end_clean ();
// 写入文件,若不可写则返回缓存
if ( is_writable ( $cachefilename ))
{
$handle = fopen ( $cachefilename , " w " );
fwrite ( $handle , $content );
fclose ( $handle );
}
else
{
return ReadCache() . " outdated " ;
}

return $content . ' newcache ' ;

}

// 读取缓存文件
function ReadCache()
{
global $cachefilename ;
$handle = fopen ( $cachefilename , " r " );
$content = '' ;
while ( ! feof ( $handle ))
{
$line = fgets ( $handle );
$content .= $line ;
}
fclose ( $handle );
return $content . ' cachedat ' . date ( " Y-m-dH:i:s " , filemtime ( $cachefilename ));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值