php 静态页缓存
<?php//缓存文件保存路径 注意此路径需要手动创建
$cache_dir = dirname(__FILE__).'/phpcache/';
//以下是PHP创建文件夹程序
if(!file_exists($cache_dir))
{
mkdir($cache_dir,0777);
}
//缓存KEY
$cache_key = 'index';
//缓存时间 秒
$cache_time = 600;
//是否需要加载缓存
$cache_reload = false;
//如果缓存文件不存在,则重新生成缓存
if(!file_exists($cache_dir.$cache_key))
{
$cache_reload = true;
}
else
{
//如果当前时间大于(缓存文件创建时间+缓存时间),说明缓存过期,需要重新生成缓存
//time() filemtime() 均返回Unix 时间戳
if(time() > (filemtime($cache_dir.$cache_key) + $cache_time))
{
$cache_reload = true;
}
}
//是否生成新缓存或是加载缓存文件
if(!$cache_reload) //加载缓存文件输出
{
echo file_get_contents($cache_dir.$cache_key);
}
else
{ //重新生成缓存文件并输出
ob_start();
//以下是原来的程序
echo 'index page';
//程序结束
//取得缓存区内容
$content = ob_get_contents();
//清除缓存区内容
ob_clean();
file_put_contents($cache_dir.$cache_key,$content);
echo $content;
///特别说明
//$cache_dir.$cache_key 只要涉及到文件操作,请给出全部文件路径。
}