<?php
$_time =5;//缓存有效时间
$dir="";//当前目录下生成缓存文件,便于测试
function cache_start($_time, $dir)
{
$cachefile = $dir.sha1($_SERVER['REQUEST_URI']).'.html';
$cachetime = $_time;
ob_start();
/*-------------------------
**判断:1.缓存文件存在并且
** 2.未过期
--------------------------*/
if(file_exists($cachefile) && (time( )-$cachetime < filemtime($cachefile)))
{
include($cachefile);
ob_end_flush();
exit;
}
}
function cache_end($dir)
{
$cachefile = $dir.sha1($_SERVER['REQUEST_URI']).'.html';
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
cache_start($_time, $dir);
//以下是输出的内容,放在cache_start和cache_end两个方法之间
for($i=0;$i<=100;$i++)
{
for($j=0;$j<=$i;$j++)echo $j."-";
echo "<br>";
}
cache_end($dir);
$_time =5;//缓存有效时间
$dir="";//当前目录下生成缓存文件,便于测试
function cache_start($_time, $dir)
{
$cachefile = $dir.sha1($_SERVER['REQUEST_URI']).'.html';
$cachetime = $_time;
ob_start();
/*-------------------------
**判断:1.缓存文件存在并且
** 2.未过期
--------------------------*/
if(file_exists($cachefile) && (time( )-$cachetime < filemtime($cachefile)))
{
include($cachefile);
ob_end_flush();
exit;
}
}
function cache_end($dir)
{
$cachefile = $dir.sha1($_SERVER['REQUEST_URI']).'.html';
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}
cache_start($_time, $dir);
//以下是输出的内容,放在cache_start和cache_end两个方法之间
for($i=0;$i<=100;$i++)
{
for($j=0;$j<=$i;$j++)echo $j."-";
echo "<br>";
}
cache_end($dir);
本文介绍了一种使用PHP实现的简单页面缓存机制。该机制通过生成特定的缓存文件来存储页面输出内容,并在下次请求时检查该缓存是否有效。如果缓存有效且未过期,则直接输出缓存内容,避免重复计算,从而提高网站响应速度。
153

被折叠的 条评论
为什么被折叠?



