緩存
背景頁面:
<?php
//緩存:不讀資料庫,直接顯示一個靜态頁面。優點通路速度快,缺點不能及時的更新顯示,用在對資料庫操作對于使用者浏覽體驗不影響的地方,緩存檔案在cache檔案夾裡面(把緩存好的靜态頁面直接顯示出來)
//1.定義一個該頁面的緩存檔案路徑
$filename = "../cache/testhuancun.html";
//2.設定緩存時間
$time=5;
//3.判斷這個緩存檔案是否存在,存在讀取緩存檔案,不存在走查詢資料庫代碼
if(!file_exists($filename) || filemtime($filename)+$time<time())//緩存檔案不存在或者修改時間+5秒小于目前時間的時候走if,設定5秒的緩存間隔時間
{
//開啟記憶體緩存
ob_start();
include("../init.inc.php");
include("../DBDA.php");
$db = new DBDA();
$sql = "select * from nation";
$attr = $db->Query($sql);
$smarty->assign("nation",$attr);
$smarty->display("test.html");
//把記憶體裡面的内容讀出來
$nr = ob_get_contents();
//将讀到的内容存放到緩存檔案
file_put_contents($filename,$nr);
//清除記憶體緩存
ob_flush();
echo "##############################"; //如果顯示echo輸出的内容,說明5秒緩存時間已過期,使用者再浏覽網頁,走資料庫,如果不顯示的話說明緩存還沒到期,走else,直接調取靜态頁面顯示
}
else
{
include($filename);
}
<body>
<table width="100%" border="1">
<tr><td>代号</td><td>名稱</td></tr>
<{foreach $nation as $v}>
<tr>
<td><{$v[0]}></td>
<td><{$v[1]}></td>
</tr>
<{/foreach}>
</table>
</body>