
正文
六、smarty-缓存控制前的页面静态化原理
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
页面静态化可以实现优化服务,对大流量访问网站非常至关重要
为什么页面静态化,
1、 不去执行数据库连接
2、 不去执行SQL语句
设置按时间更新,
1、 按时间更新,如果缓存文件设置1小时
如下为页面静态化原理实例:
//内容分页显示实例
<?php$cachefile = "demo_".$get["page"].".html"; //定义的缓存文件用于存放静态页面, $get["page"]表示将每一分页都缓存
$cachetime=20; //设置更新时间,单位是秒if(!file_exists($cachefile) || filemtime($cachefile)+$cachetime<time()) //如果缓存文件不存在(或时间过期)则执行数据库查询输出 //开启缓存,将输出内容存入内存
ob_start(); //链接数据库
try{
$PDO = new PDO('mysql:host=localhost;dbname=access_control', 'root', 'password');
}catch(PDOException $e){
echo $e->getMessage();
exit;
} //查询语句
$sql = "select * from access_user";
$stnt = $PDO->prepare($sql); $stnt->execute(); //组合成html输出
echo '<table border="1" width="400" align="align">';
echo '<caption><h1>USER</h1></caption>';
while(list($id,$name,$age,$email) = $stnt->fetch(PDO::FETCH_NUM))
{
echo '<tr>';
echo '<td>'.$id.'</td>';
echo '<td>'.$name.'</td>';
echo '<td>'.$age.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
echo '</table>'; //将所有在内存中缓存的内容保存到变量$html中
$html = ob_get_content();
file_put_contents($cachefile,$html); //输出到缓存静态页面中 //输出所有内存中的内容到客户端;
ob_flush();}else{
include $cachefile; //如果缓存文件存在直接加载缓存文件
}






