後臺:php
<?php //要求:當存在緩存文件,直接輸出,不存在緩存文件,本身建立緩存,輸出 //步驟: //定義該頁面存放緩存文件的路徑 $filename="../../cache/cache.html"; //定義緩存有效期 $cachetime=5; //判斷是否存在緩存或是否過時 if(!file_exists($filename) || time()-filemtime($filename)>$cachetime)//如今的時間-緩存建立時間 { //開啓內存緩存--將下面執行後的頁面代碼存到內存 ob_start(); include ('../../init.inc.php'); include ("../../DBDA.php"); $dx=new DBDA(); $sql="select * from car"; $attr=$dx->Query($sql); $smarty->assign("car",$attr); $smarty->display("main.html"); //獲取內存緩存裏的頁面代碼 $content=ob_get_contents(); //將頁面代碼存到緩存文件裏 file_put_contents($filename,$content); //清除內存緩存並輸出顯示 ob_flush(); echo "#########";//表明第一次執行 } else { include ($filename);//若是存在緩存,直接讀取 } //若是刷新頁面沒有改變的話,多是有緩存文件,爲了不這樣,需設置緩存有效期
前臺:html
<body> <table border="1" width="80%" align="center" cellpadding="0" cellspacing="0"> <tr> <th>代號</th> <th>汽車名稱</th> <th>油耗</th> <th>價格</th> </tr> <{foreach $car as $v}> <tr> <td><{$v[0]}></td> <td><{$v[1]}></td> <td><{$v[4]}></td> <td><{$v[7]}></td> </tr> <{/foreach}> </table> </body>
分頁緩存:sql
後臺:緩存
<?php //分頁緩存 //要求:實現每一頁都緩存 //步驟: //取當前頁 $p=1; if(!empty($_GET["page"])) { $p = $_GET["page"]; } //定義緩存文件存放路徑 $filename = "../../cache/cahetesta{$p}.html"; //定義緩存有效期 $cachetime=5; //判斷緩存是否存在或是否過時 if(!file_exists($filename) || time()-filemtime($filename)>$cachetime) { ob_start();//開啓內存緩存 include("../../init.inc.php"); include("../../DBDA.php"); $db = new DBDA(); include("../../page.class.php"); $szs = "select count(*) from car"; $zs = $db->StrQuery($szs); $page = new Page($zs,5); $xinxi = $page->fpage(); $sql = "select * from car ".$page->limit; $attr = $db->Query($sql); $smarty->assign("car",$attr); $smarty->assign("xinxi",$xinxi); $smarty->display("maina.html"); //獲取內存緩存頁面代碼 $nr = ob_get_contents(); //將頁面代碼存放到緩存文件下 file_put_contents($filename,$nr); //清除內存緩存並輸出 ob_flush(); echo "##########################";//用來檢查是不是第一次訪問或過時與否 } else { include($filename); }
前臺:spa
<body> <h1>汽車信息</h1> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>代號</td> <td>汽車名稱</td> <td>油耗</td> <td>價格</td> </tr> <{foreach $car as $v}> <tr> <td><{$v[0]}></td> <td><{$v[1]}></td> <td><{$v[4]}></td> <td><{$v[7]}></td> </tr> <{/foreach}> </table> <div><{$xinxi}></div> </body>