天天看點

PHP使用緩存生成靜态頁面

靜态網址與動态網址

①    靜态網址

http://localhost/test2.html

②    動态網址

http://localhost/showNews.php?id=2&title=hello

③    僞靜态網址

傳統的做法->動态網址

http://localhost/news-cn-sport-id100.html

頁面靜态化的分類

為什麼要靜态化

1.      通路php的速度比html慢

在apache / bin/ab.exe  可以做壓力測試,該工具可以模拟多人,并發通路某個頁面.

基本的用法

 ab.exe –n 10000 –c 10 http://localhost/test.php

-n 表示請求多少次

-c 表示多少人

2.      靜态化利于seo

3.     防止sql注入

①    真靜态

方法1: 使用php自身的緩存機制

如果要測試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緩存控制的幾個函數:

//PHP緩存控制的幾個函數:
//開啟緩存 [通過php.ini,也可以在頁面 ob_start()]
ob_start();
echo "yyy";
header("content-type:text/htm;charset=utf-8");
echo "hello";
//ob_clean函數可以清空 outputbuffer的内容.
//ob_clean();
//ob_end_clean是關閉ob緩存,同時清空.
//ob_clean();
//ob_end_flush() 函數是 把ob緩存的記憶體輸出,并關閉ob
//ob_end_flush();
//ob_end_flush() 函數是 把ob緩存的記憶體輸出,
//ob_flush()函數是輸出ob内容,并清空,但不關閉.
ob_flush();
		
echo "kkk";//=>ob緩存.

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

//ob_get_contents() 可以擷取output_buffering的内容.
//$contents=ob_get_contents();

//file_put_contents("d:/log.text",$contents);
           

下面來看一個執行個體,用緩存技術,"假如儲存的緩存檔案未超過30秒,則直接取出緩存檔案":

<?php
                $id=$_GET['id'];
                $filename="static_id_".$id.".html";
                $status=filemtime($filename)+30>time();//判斷檔案建立及修改時間距目前時間是否超過30秒
                if(file_exists($filename)&&$status){
                    $str=file_get_contents($filename);
                    echo $str;
                }else{
                    require_once "SqlHelper.class.php";
                    $sqlHelper=new Sqlhelper();
                    $arr=$sqlHelper->execute_dql2("SELECT * FROM news1 WHERE id=$id");
                    if(empty($arr)){
                        echo "資料為空";
                    }else{
                        /***緩存開始***/
                        ob_start();//下面的内容将存到緩存區中,顯示的内容都将存到緩存區
                        echo $arr[0]['tile'];
                        echo "<br/>";
                        echo $arr[0]['content'];
                        $content=  ob_get_contents();//從緩存中擷取内容
                        ob_end_clean();//關閉緩存并清空
                        /***緩存結束***/
                        file_put_contents($filename, $content);
                        echo $content;
                    }
                }
                
                
            ?>