PHP缓存技术

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<?php

//定义该页面缓存文件存放的路径
$filename = "huancun.php";

//定义缓存有效期
$cachetime = 5;

//判断缓存文件是否存在
if(!file_exists($filename) || filemtime($filename)+$cachetime<time())  //filemtime($filename)获取文件修改时间,加上定义的缓存时间小于当前时间
{
    //开启内存缓存
    ob_start();
    
    include("DBDA.php");
    $db = new DBDA();
    
    $sql = "select * from nation";
    
    $attr = $db->Query($sql);
    
     foreach($attr as $v)
    {
        echo "<div>{$v[1]}</div>";
    }
    
    //从内存缓存中获取页面代码
    $content = ob_get_contents();
    
    //将获取到的内容存放到缓存文件
    file_put_contents($filename,$content);
    
    //清掉内存缓存
    ob_flush();
    
    echo "######################################";  //测试是否调用了缓存文件,缓存文件不输出这句话

}
else
{
    include($filename);  //如果存在,调用缓存文件
}
?>
</body>
</html>
View Code

 

posted @ 2016-12-18 11:33  哔哩哔哩干杯  阅读(176)  评论(0编辑  收藏  举报