class ArrCache(string path,[int time],[string type]);
* path: cache文件保存目录,从根目录算起,首尾不需要“/”
* time: 缓存时间,默认120秒
* type: 缓存文件后缀,默认“txt”
*
* void endCache();
* 在页面最后写上,否则这行后边的数据不会被缓存。
*
*/
ob_start();
class ArrCache
{
//构造函数
function ArrCache($path,$time = 120,$type = 'txt')
{
$this->path = $path;
$this->time = $time;
$this->fileType = $type;
$this->fileName = $_SERVER['DOCUMENT_ROOT'].'\\'.$this->path.'\\'.md5($_SERVER['URL'].'?'.$_SERVER['QUERY_STRING']).'.'.$this->fileType;
if (file_exists($this->fileName) && ((filemtime($this->fileName)+$this->time) > time()))
{
$fp = fopen($this->fileName,"r");
echo fread($fp,filesize($this->fileName));
fclose($fp);
ob_end_flush();
exit;
}
}
//在文件最后加入这行,输出所有缓存内容,并且写入缓存文件。
function endCache()
{
$fp = fopen($this->fileName,"w");
fwrite($fp,ob_get_contents());
fclose($fp);
ob_end_flush();
}
}
/********演示代码********/
$cache = new ArrCache('cache',5,'txt');
for ($i=0;$i<5;$i++)
{
echo $i;
sleep(1);
}
$cache->endCache();