php頁面緩衝方法小結_php技巧

來源:互聯網
上載者:User

本文執行個體總結了php頁面緩衝方法。分享給大家供大家參考。具體分析如下:

在php頁面緩衝主要用到的是ob系列函數,如ob_start(),ob_end_flush(),ob_get_contents(),但是更進階的緩衝是不使用這些函數的,本文最後會舉一個執行個體加以說明.

先來看看緩衝常用的ob系列函數:

ob_start():頁面緩衝開始的標誌,此函數一下的內容直至ob_end_flush()或者ob_end_clean()都儲存在頁面緩衝中;

ob_get_contents():用來擷取頁面緩衝中的內容,擷取到以後呢,我們就可以想怎麼處理這些內容都行了,過濾欄位啦,匹配內容啦,都可以~~~

ob_end_flush():表示頁面緩衝結束,並且經我驗證,緩衝的內容將輸出到當前頁面上,也就是可以顯示緩衝內容.

用此三個php函數,就可以實現強大的功能,如果資料庫查詢量較大,可以用cache來解決這個問題.

下面是編碼部分.

1.初始化函數,一般是設定頁面緩衝路徑、快取檔案命名格式等,可按個人喜好自訂,這裡用到的識別ID是經加密的$_SERVER[REQUEST_URI]參數,這個函數中最後還有一個if判斷,若未過緩衝期,則載入快取檔案,否則載入源檔案,代碼如下:

複製代碼 代碼如下:
function page_init()
{    
     $url = $_SERVER['REQUEST_URI'];//子url,該參數一般是唯一的
     $pageid = md5($url);
     $dir = str_replace('/','_',substr($_SERVER['SCRIPT_NAME'],1,-4));
         //目錄命名方式,如exp_index
     if(!file_exists($pd = PAGE_PATH.$dir.'/'))@mkdir($pd,0777) or die("$pd目錄建立失敗");
         //如cache/page/exp_index/
     define('PAGE_FILE',$pd.$pageid.'.html');
       //如cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html
     $contents = file_get_contents(PAGE_FILE);//讀出
 
     if($contents && substr($contents, 13, 10) > time() )//對應page_cache()函數中加上的自訂頭部
     {
         echo substr($contents, 27);
         exit(0);
     }
     return true;    
}

2.頁面緩衝函數,這裡使用到一個技巧,在快取檔案的內容中加上一個頭部資訊--到期時間,所以每次只需要對頭部中的到期時間和目前時間進行比較,在page_init()函數中進行,就能判斷緩衝是否到期了,代碼如下:
複製代碼 代碼如下:
function page_cache($ttl = 0)
{
     $ttl = $ttl ? $ttl : PAGE_TTL;//緩衝時間,預設3600s
     $contents = ob_get_contents();//從緩衝中擷取內容
     $contents = "<!--page_ttl:".(time() + $ttl)."-->n".$contents;
       //加上自訂頭部:到期時間=產生時間+緩衝時間
     file_put_contents(PAGE_FILE, $contents);//寫入快取檔案中
     ob_end_flush();//釋放緩衝
}

3.函數使用,注意這兩個函數有先後執行順序,還有別忘了ob_start(),代碼如下:
複製代碼 代碼如下:
<?php
      page_init();//頁面緩衝初始化
      ob_start();//開啟緩衝        
  
      ...//程式碼片段
  
      page_cache(60);//一般是最後一行
  
?>

例2,下面做個樣本來說明PHP頁面緩衝技術,代碼如下:
複製代碼 代碼如下:
<?php
$_time =10;
$dir="D:\php\";
 
function cache_start($_time, $dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $cachetime = $_time;
  ob_start();
  if(file_exists($cachefile) && (time()-filemtime($cachefile) < $cachetime))
  {
    include($cachefile);
    ob_end_flush();
    exit;
  }
}
 
function cache_end($dir)
{
  $cachefile = $dir.'/'.sha1($_SERVER['REQUEST_URI']).'.html';
  $fp = fopen($cachefile, 'w');
  fwrite($fp, ob_get_contents());
  fclose($fp);
  ob_end_flush();
}
 
cache_start($_time, $dir);
//以下是輸出的內容,放在cache_start和cache_end兩個方法之間
for ($i=0;$i<5;$i++)
{
  echo $i;
  sleep(1);
}
cache_end($dir);
?>

例,利用組建檔案做緩衝,代碼如下:
複製代碼 代碼如下:
<?php
ob_start();
/**
* @author 何名慧
* @copyright 2009-3-13
* @param string $cache_folder 緩檔案夾
* @param int $cache_create_time 檔案快取時間
* @example $cache=new Esj_Cache('./_cache',100)
* @example $cache->read_cache() 讀取緩衝並輸出
* @example $cache->creatre_cache() 建立快取檔案(放在檔案未尾)
* @example $cache->list_file() 返回所有快取檔案列表
* @example $cache->del_file() 刪除所有快取檔案
*/
 
class Esj_Cache{
private $cache_folder=null;//cacher檔案夾
private $wroot_dir=null;//網站目錄
private $cacher_create_time=null;//cacher檔案的建立時間
 
public function __construct($cache_foldername,$cacher_time=100)
{
ob_start();
$this->wroot_dir=$_SERVER['DOCUMENT_ROOT'];
$this->cache_folder=$cache_foldername;
$this->cacher_create_time=$cacher_time;
}
 
public function read_cache()
{
try {
if(self::create_folder($this->cache_folder))
{
self::get_cache();//輸出快取檔案資訊
}else
{
echo "快取檔案夾建立失敗!";
return false;
}
 
}catch(Exception $e){
echo $e;
return false;
}
}
 
//測試快取檔案夾是否存在
private function exist_folder($foler)
{
if(file_exists($this->wroot_dir."/".$foler)){
return true;
}else {
return false;
}
}
 
//建立一個新的檔案夾
private function create_folder($foler)
{
if(!self::exist_folder($foler))
{
try{
mkdir($this->wroot_dir."/".$foler,0777);
chmod($this->wroot_dir."/".$foler,0777);
return true;
}catch (Exception $e)
{
self::get_cache();//輸出緩衝
return false;
}
return false;
}
else
{
return true;
}
}
 
//讀取快取檔案
private function get_cache()
{
$file_name=self::get_filename();
if (file_exists($file_name)&&((filemtime($file_name)+$this->cacher_create_time) > time()))
{
$content=file_get_contents($file_name);
if($content)
{
echo $content;
ob_end_flush();
exit;
}else
{
echo "檔案讀取失敗";
exit;
 
}
 
}
}
 
//返迴文件的名字
private function get_filename()
{
$filename=$file_name=$this->wroot_dir.'/'.$this->cache_folder.'/'.md5($_SERVER['QUERY_STRING']).".html";
return $filename;
}
 
//建立快取檔案
public function create_cache()
{
$filename=self::get_filename();
if($filename!="")
{
try{
file_put_contents($filename,ob_get_contents());
return true;
}catch (Exception $e)
{
echo "寫緩衝失敗:".$e;
exit();
}
return true;
}
}
 
// 取得緩衝中的所有檔案
public function list_file()
{
$path=$this->cache_folder;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if($file!="." && $file!="..") {
$path1=$path."/".$file;
if(file_exists($path1))
{
$result[]=$file;
}
}
}
closedir($handle);
}
return $result;
}
 
//刪除緩衝中的所有檔案
public function del_file()
{
$path=$this->cache_folder;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if($file!="." && $file!="..") {
$path1=$path."/".$file;
if(file_exists($path1))
{
unlink($path1);
}
}
}
closedir($handle);
}
return true;
}
 
}
 
?>

希望本文所述對大家的php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.