全页面静态化缓存

 

打开php.ini配置文件查看output_buffering参数有没有打开output_buffering = on oroutput_buffering = 数值

 我的目录结构随便搞都可以分清楚静态和动态页面就可以

 

singwa.php  动态页面

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新闻中心</title>
<link rel="stylesheet" href="public/css/bootstrap.min.css" type="text/css">
</head>
<body>
<div class="container">
<h3>新闻列表</h3>
<ul class="list-group">
<?php foreach ($news as $key => $value) { ?>
<li class="list-group-item"><a href="#"><?php echo $value[5];?></a></li>
<?php } ?>
</ul>
</div>
</body>
</html>

index.php
//1、连接数据库,然后从数据库里面获取数据
//2、把获取到的数据填充到模板文件里面
//3、需要把动态的页面转化为静态页面,生成纯静态化文件
if(is_file('index.shtml') && (time() - filemtime('index.shtml')) < 20) { //设置缓存失效时间  time当前时间-filemtime最后修改时间<20秒 则使用缓存文件 否则重新生成静态文件
require_once('index.shtml');
} else {
require_once('db.php');

$connect = Db::getInstance()->connect();
$sql = "SELECT * FROM news WHERE `category_id` = 1 AND `status` = 1 ORDER BY id LIMIT 5";
$result = mysql_query($sql, $connect);
$news = array();
while($row = mysql_fetch_array($result)) {
$news[] = $row;
}

//print_r($news);

ob_start(); //开启缓存区

//引入模板文件
require_once('templates/singwa.php'); //动态文件 singwa.php界面同样进过缓冲区
file_put_contents('index.shtml', ob_get_contents());
/*if(file_put_contents('index.shtml', ob_get_clean())) {
echo 'success';
} else {
echo 'error';
}*/
}


posted @ 2018-04-03 17:14  刹那风华——  阅读(275)  评论(0编辑  收藏  举报