PHP使用緩存生成靜態頁面


 

在apache / bin/ab.exe  可以做壓力測試,該工具可以模擬多人,並發訪問某個頁面.

 

基本的用法

 ab.exe –n 10000 –c 10

-n 表示請求多少次

-c 表示多少人

如果要測試php自己的緩存機制, 需要做配置.

php.ini 文件

display_errors=On

output_buffering=Off

error_reproting= 設置錯誤級別

 

看一段代碼,使用緩存時,在發送文件頭之前可以顯示文字.

<?php

              echo“yyy”;

              header(“content-type:text/htm;charset=utf-8”);

              echo“hello”;

?>

PHP緩存控制的幾個函數:

 

 1 //PHP緩存控制的幾個函數:
 2 //開啟緩存 [通過php.ini,也可以在頁面 ob_start()]
 3 ob_start();
 4 echo "yyy";
 5 header("content-type:text/htm;charset=utf-8");
 6 echo "hello";
 7 //ob_clean函數可以清空 outputbuffer的內容.
 8 //ob_clean();
 9 //ob_end_clean是關閉ob緩存,同時清空.
10 //ob_clean();
11 //ob_end_flush() 函數是 把ob緩存的內存輸出,並關閉ob
12 //ob_end_flush();
13 //ob_end_flush() 函數是 把ob緩存的內存輸出,
14 //ob_flush()函數是輸出ob內容,並清空,但不關閉.
15 ob_flush();
16         
17 echo "kkk";//=>ob緩存.
18 
19 //header("content-type:text/htm;charset=utf-8");
20 
21 //ob_get_contents() 可以獲取output_buffering的內容.
22 //$contents=ob_get_contents();
23 
24 //file_put_contents("d:/log.text",$contents);

 

下面來看一個實例,用緩存技術,"假如保存的緩存文件未超過30秒,則直接取出緩存文件":

 

 1 <?php
 2                 $id=$_GET['id'];
 3                 $filename="static_id_".$id.".html";
 4                 $status=filemtime($filename)+30>time();//判斷文件創建及修改時間距當前時間是否超過30秒
 5                 if(file_exists($filename)&&$status){
 6                     $str=file_get_contents($filename);
 7                     echo $str;
 8                 }else{
 9                     require_once "SqlHelper.class.php";
10                     $sqlHelper=new Sqlhelper();
11                     $arr=$sqlHelper->execute_dql2("SELECT * FROM news1 WHERE id=$id");
12                     if(empty($arr)){
13                         echo "數據為空";
14                     }else{
15                         /***緩存開始***/
16                         ob_start();//下面的內容將存到緩存區中,顯示的內容都將存到緩存區
17                         echo $arr[0]['tile'];
18                         echo "<br/>";
19                         echo $arr[0]['content'];
20                         $content=  ob_get_contents();//從緩存中獲取內容
21                         ob_end_clean();//關閉緩存並清空
22                         /***緩存結束***/
23                         file_put_contents($filename, $content);
24                         echo $content;
25                     }
26                 }
27                 
28                 
29             ?>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM