PHP中的ob_start用法詳解

用PHP的ob_start();
控制您的瀏覽器cache


Output Control 函數可以讓你自由控制腳本中數據的輸出。它非常地有用,特別是對于:當你想在數據已經輸出后,再輸出文件頭的情況。輸出控制函數不對使用 header() 或 setcookie(), 發送的文件頭信息產生影響,只對那些類似于 echo() 和 PHP 代碼的數據塊有作用。
我們先舉一個簡單的例子,讓大家對Output Control有一個大致的印象:
Example 1.

程序代碼 程序代碼
<?php
ob_start(); //打開緩沖區
echo \"Hellon\"; //輸出
header("location:index.php"); //把瀏覽器重定向到index.php
ob_end_flush();//輸出全部內容到瀏覽器
?>


所有對header()函數有了解的人都知道,這個函數會發送一段文件頭給瀏覽器,但是如果在使用這個函數之前已經有了任何輸出(包括空輸出,比如空格,回車和換行)就會提示出錯。如果我們去掉第一行的ob_start(),再執行此程序,我們會發現得到了一條錯誤提示:"Header had all ready send by"!但是加上ob_start,就不會提示出錯,原因是當打開了緩沖區,echo后面的字符不會輸出到瀏覽器,而是保留在服務器,直到你使用 flush或者ob_end_flush才會輸出,所以并不會有任何文件頭輸出的錯誤!


一、 相關函數簡介:
1、Flush:刷新緩沖區的內容,輸出。
函數格式:flush()
說明:這個函數經常使用,效率很高。
2、ob_start :打開輸出緩沖區
函數格式:void ob_start(void)
說明:當緩沖區激活時,所有來自PHP程序的非文件頭信息均不會發送,而是保存在內部緩沖區。為了輸出緩沖區的內容,可以使用ob_end_flush()或flush()輸出緩沖區的內容。
3 、ob_get_contents :返回內部緩沖區的內容。
使用方法:string ob_get_contents(void)
說明:這個函數會返回當前緩沖區中的內容,如果輸出緩沖區沒有激活,則返回 FALSE 。
4、ob_get_length:返回內部緩沖區的長度。
使用方法:int ob_get_length(void)
說明:這個函數會返回當前緩沖區中的長度;和ob_get_contents一樣,如果輸出緩沖區沒有激活。則返回 FALSE。
5、ob_end_flush :發送內部緩沖區的內容到瀏覽器,并且關閉輸出緩沖區。
使用方法:void ob_end_flush(void)
說明:這個函數發送輸出緩沖區的內容(如果有的話)。
6、ob_end_clean:刪除內部緩沖區的內容,并且關閉內部緩沖區
使用方法:void ob_end_clean(void)
說明:這個函數不會輸出內部緩沖區的內容而是把它刪除!
7、ob_implicit_flush:打開或關閉絕對刷新
使用方法:void ob_implicit_flush ([int flag])
說明:使用過Perl的人都知道$|=x的意義,這個字符串可以打開/關閉緩沖區,而ob_implicit_flush函數也和那個一樣,默認為關閉緩沖區,打開絕對輸出后,每個腳本輸出都直接發送到瀏覽器,不再需要調用 flush()


二、深入了解:

1. 關于Flush函數:
這個函數在PHP3中就出現了,是一個效率很高的函數,他有一個非常有用的功能就是刷新browser的cache.我們舉一個運行效果非常明顯的例子來說明flush.
Example 2.

程序代碼 程序代碼
<?php
for($i = 1; $i <= 300; $i++ ) print(" ");
// 這一句話非常關鍵,cache的結構使得它的內容只有達到一定的大小才能從瀏覽器里輸出
// 換言之,如果cache的內容不達到一定的大小,它是不會在程序執行完畢前輸出的。經
// 過測試,我發現這個大小的底限是256個字符長。這意味著cache以后接收的內容都會
// 源源不斷的被發送出去。
For($j = 1; $j <= 20; $j++) {
echo $j."
";
flush(); //這一部會使cache新增的內容被擠出去,顯示到瀏覽器上
sleep(1); //讓程序"睡"一秒鐘,會讓你把效果看得更清楚
}
?>

注:如果在程序的首部加入ob_implicit_flush()打開絕對刷新,就可以在程序中不再使用flush(),這樣做的好處是:提高效率!

2. 關于ob系列函數:
我想先引用我的好朋友y10k的一個例子:
Example 3.

比如你用得到服務器和客戶端的設置信息,但是這個信息會因為客戶端的不同而不同,如果想要保存phpinfo()函數的輸出怎么辦呢?在沒有緩沖區控制之前,可以說一點辦法也沒有,但是有了緩沖區的控制,我們可以輕松的解決:
程序代碼 程序代碼
<?php
ob_start(); //打開緩沖區
phpinfo(); //使用phpinfo函數
$info=ob_get_contents(); //得到緩沖區的內容并且賦值給$info
$file=fopen(\'info.txt\',\'w\'); //打開文件info.txt
fwrite($file,$info); //寫入信息到info.txt
fclose($file); //關閉文件info.txt
?>

?

用以上的方法,就可以把不同用戶的phpinfo信息保存下來,這在以前恐怕沒有辦法辦到!其實上面就是將一些"過程"轉化為"函數"的方法!
或許有人會問:"難道就這個樣子嗎?還有沒有其他用途?"當然有了,比如筆者論壇的PHP 語法加亮顯示就和這個有關(PHP默認的語法加亮顯示函數會直接輸出,不能保存結果,如果在每次調用都顯示恐怕會很浪費CPU,筆者的論壇就把語法加亮函數顯示的結果用控制緩沖區的方法保留了),大家如果感興趣的話可以來看看

可能現在大家對ob_start()的功能有了一定的了解,上面的一個例子看似簡單,但實際上已經掌握了使用ob_start()的要點。
<1>.使用ob_start打開browser的cache,這樣可以保證cache的內容在你調用flush(),ob_end_flush()(或程序執行完畢)之前不會被輸出。
<2>.現在的你應該知道你所擁有的優勢:可以在任何輸出內容后面使用header,setcookie以及session,這是 ob_start一個很大的特點;也可以使用ob_start的參數,在cache被寫入后,然后自動運行命令,比如ob_start(\ "ob_gzhandler\");而我們最常用的做法是用ob_get_contents()得到cache中的內容,然后再進行處理……
<3>.當處理完畢后,我們可以使用各種方法輸出,flush(),ob_end_flush(),以及等到程序執行完畢后的自動輸出。當然,如果你用的是ob_get_contents(),那么就要你自己控制輸出方式了。

來,讓我們看看能用ob系列函數做些什么……

一、 靜態模版技術

簡介:所謂靜態模版技術就是通過某種方式,使得用戶在client端得到的是由PHP產生的html頁面。如果這個html頁面不會再被更新,那么當另外的用戶再次瀏覽此頁面時,程序將不會再調用PHP以及相關的數據庫,對于某些信息量比較大的網站,例如sina,163,sohu。類似這種的技術帶來的好處是非常巨大的。

我所知道的實現靜態輸出的有兩種辦法:
<1>.通過y10k修改的phplib的一個叫template.inc.php類實現。
<2>.使用ob系列函數實現。
對于第一種方法,因為不是這篇文章所要研究的問題,所以不再贅述。
我們現在來看一看第二種方法的具體實現:
Example 4.


程序代碼 程序代碼
<?php
ob_start();//打開緩沖區
?>
php頁面的全部輸出
<?
$content = ob_get_contents();//取得php頁面輸出的全部內容
$fp = fopen("output00001.html", "w"); //創建一個文件,并打開,準備寫入
fwrite($fp, $content); //把php頁面的內容全部寫入output00001.html,然后……
fclose($fp);
?>


這樣,所謂的靜態模版就很容易的被實現了……

二、 捕捉輸出

以上的Example 4.是一種最簡單的情況,你還可以在寫入前對$content進行操作……
你可以設法捕捉一些關鍵字,然后去對它進行再處理,比如Example 3.所述的PHP語法高亮顯示。個人認為,這個功能是此函數最大的精華所在,它可以解決各種各樣的問題,但需要你有足夠的想象力……
Example 5.

程序代碼 程序代碼
<?php
Function run_code($code) {
If($code) {
ob_start();
eval($code);
$contents = ob_get_contents();
ob_end_clean();
}else {
echo "錯誤!沒有輸出";
exit();
}
return $contents;
?>
}

?

以上這個例子的用途不是很大,不過很典型$code的本身就是一個含有變量的輸出頁面,而這個例子用eval把$code中的變量替換,然后對輸出結果再進行輸出捕捉,再一次的進行處理……

Example 6. 加快傳輸


程序代碼 程序代碼
<?
/*
** Title.........: PHP4 HTTP Compression Speeds up the Web
** Version.......: 1.20
** Author........: catoc <catoc@163.net>
** Filename......: gzdoc.php
** Last changed..: 18/10/2000
** Requirments...: PHP4 >= 4.0.1
** PHP was configured with --with-zlib[=DIR]
** Notes.........: Dynamic Content Acceleration compresses
** the data transmission data on the fly
** code by sun jin hu (catoc) <catoc@163.net>
** Most newer browsers since 1998/1999 have
** been equipped to support the HTTP 1.1
** standard known as \"content-encoding.\"
** Essentially the browser indicates to the
** server that it can accept \"content encoding\"
** and if the server is capable it will then
** compress the data and transmit it. The
** browser decompresses it and then renders
** the page.
**
** Modified by John Lim (jlim@natsoft.com.my)
** based on ideas by Sandy McArthur, Jr
** Usage........:
** No space before the beginning of the first \'<?\' tag.
** ------------Start of file----------
** |<?
** | include(\'gzdoc.php\');
** |? >
** |<HTML>
** |... the page ...
** |</HTML>
** |<?
** | gzdocout();
** |? >
** -------------End of file-----------
*/
ob_start();
ob_implicit_flush(0);
function CheckCanGzip(){
global $HTTP_ACCEPT_ENCODING;
if (headers_sent() || connection_timeout() || connection_aborted()){
return 0;
}
if (strpos($HTTP_ACCEPT_ENCODING, \'x-gzip\') !== false) return \"x-gzip\";
if (strpos($HTTP_ACCEPT_ENCODING,\'gzip\') !== false) return \"gzip\";
return 0;
}
/* $level = compression level 0-9, 0=none, 9=max */
function GzDocOut($level=1,$debug=0){
$ENCODING = CheckCanGzip();
if ($ENCODING){
print \"n<!-- Use compress $ENCODING -->n\";
$Contents = ob_get_contents();
ob_end_clean();
if ($debug){
$s = \"<p>Not compress length: \".strlen($Contents);
$s .= \"
Compressed length: \".strlen(gzcompress($Contents,$level));
$Contents .= $s;
}
header(\"Content-Encoding: $ENCODING\");
print \"x1fx8bx08x00x00x00x00x00\";
$Size = strlen($Contents);
$Crc = crc32($Contents);
$Contents = gzcompress($Contents,$level);
$Contents = substr($Contents, 0, strlen($Contents) - 4);
print $Contents;
print pack(\'V\',$Crc);
print pack(\'V\',$Size);
exit;
}else{
ob_end_flush();
exit;
}
}
?>

轉載于:https://www.cnblogs.com/simadi/p/3156371.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/274184.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/274184.shtml
英文地址,請注明出處:http://en.pswp.cn/news/274184.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

做事用人 用人做事_做事:構建我的第一個Web應用程序的經驗教訓

做事用人 用人做事On the 5th of June, 2020, after almost two weeks of (re)learning javascript, fixing bugs, creating new ones and of course, lots of testing, I launched Writty on ProductHunt. An open-source text editor to help anyone who is into writing to …

[轉]C#委托的異步調用

本文將主要通過“同步調用”、“異步調用”、“異步回調”三個示例來講解在用委托執行同一個“加法類”的時候的的區別和利弊。 首先&#xff0c;通過代碼定義一個委托和下面三個示例將要調用的方法&#xff1a; /*添加的命名空間using System.Threading;using System.Runtime.…

vista下載_Vista和視圖在游戲設計中的功能

vista下載Views in video games are observation points used to highlight a lot of objects into one frame or shot using a special camera move. Vistas are special types of views that show distant objects, mainly far off landscapes.電子游戲中的視圖是觀察點&…

微軟開始提供公共預覽版Windows 8.1下載

用戶可在微軟發布官方更新時免費下載Windows 8.1&#xff0c;這個最新版本的Windows 8系統對搜索系統作出了改進&#xff0c;此外還修改了Windows Store&#xff0c;并對核心應用進行了升級。Windows 8.1還重新推出了“開始”按鈕&#xff0c;并對用戶界面作出了多處修改。雖然…

keynote使用手冊_如何使用Keynote和智能手機為AR創建原型

keynote使用手冊Designing for AR is perhaps one of the most interesting applications of UX. As this incredible technology is being put to use for unique applications, UX Designers are tasked with creating user interfaces for an augmented experience, that do…

我會永遠永遠的愛你,直到你不愛我的那一天

【one】電話鈴聲響起的時候&#xff0c;林岫正好解下衣服的最后一顆紐扣。她站在原地&#xff0c;看著桌面上不斷震動的手機&#xff0c;很久都沒有接。“林醫生&#xff0c;你的電話”&#xff0c;有同事在身旁好心的提醒。她依然沒有動&#xff0c;只是靜靜注視著那個手機&am…

HTML5工具

HTML5工具 HTML&#xff08;Hyper Text Mark-up Language &#xff09;即超文本標記語言&#xff0c;自萬維網初創之日起&#xff0c;它就已經成為滿意度很高的公共語言。在過去的兩年里&#xff0c;HTML5在性能上得到了很大的提升和改進&#xff0c;當仁不讓的獲得了大眾的青睞…

遠程控制工具_不要讓您的工具控制您

遠程控制工具When to Use Optical Alignment — You’re the Designer. You Know What’s Best.何時使用光學對準—您是設計師。 你知道什么是最好的。 Let’s talk about the tools the vast majority of us use on a day to day basis… These tools are Incredibly powerfu…

模態和非模態代碼_我們如何使模態可用和可訪問?

模態和非模態代碼什么是模態&#xff1f; (What are modals?) A modal, or modal dialog, is an overlay window that opens on top of the current primary content or screen. It places focus on itself, usually making the background inactive (“inert”) — i.e. visu…

如何查看數據文件或者Log文件是否增長過?

在論壇看到一個帖子&#xff0c;說數據庫變慢了一段時間&#xff0c;發現這段時間數據庫文件的最后修改時間跟變慢的世界一致&#xff0c;想知道這段時間是否文件確實增長了。 其實SQL Server提供了數據增長的Event&#xff0c;而且Default Trace里面就記錄了。 下面我們做個測…

軟件項目開發 學校自行開發_自行開發游戲

軟件項目開發 學校自行開發Making a game is not easy. Quite the contrary; it’s an incredibly difficult and daunting task. Game development typically takes teams of people, thousands of hours worth of labor, and hundreds of thousands — if not millions — of…

jquery Fancybox使用教程

jquery Fancybox使用教程 Fancybox是一款基于jquery的對圖片展示播放的插件&#xff0c;當然&#xff0c;它html文本、flash動畫、iframe以及ajax也予以支持。還可以通過css自定義外觀&#xff0c;陰影效果超級贊&#xff01; 演示效果&#xff1a;http://www.phpddt.com/demo/…

優衣庫不雅_Uniqlo主頁-用戶體驗案例研究

優衣庫不雅I am a big fan of Uniqlo because they sell innovative clothing that is great quality at great prices. So when all their stores closed during the “Covid-19 Circuit Breaker” in Singapore, I turned to their website and was surprised how difficult …

PHP生成縮略圖函數

function img_create_small($big_img, $width, $height, $small_img) { // 大圖文件地址&#xff0c;縮略寬&#xff0c;縮略高&#xff0c;小圖地址$imgage getimagesize($big_img); //獲取大圖信息switch ($imgage[2]) { // 判斷圖像類型case 1:$im imagecreatefromgif($bi…

shields 徽標_到處都有平面徽標

shields 徽標重點 (Top highlight)Companies invest a lot of time, money and energy trying to make audiences remember their logos and associate higher value with it. The end goal is to make customers pick their brand over another brand. 公司投入了大量的時間&a…

jquery錨點連接劃動滾動條,再也不用a標簽name 了

$("html,body").animate({ scrollTop: $(".reviews_list").children("ul").children("li").children("b:last").offset().top }, 1000); 轉載于:https://www.cnblogs.com/gxmaspx/p/3169931.html

登錄,注冊,登錄,登錄..?

Last year I found myself in an interesting conversation about which copy to use for a website’s sign up journey. And it wasn’t the first time. Often this devolves into an opinion-based discussion among stakeholders of the ‘what-I-like-based-on-no-eviden…

未完成的控件

using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms;namespace ImageControls {/// <summary>/// 控件/// </summary> public class ShapeEx : Control{#region 字段private Color _B…

ux設計_UX設計101:

ux設計這是什么&#xff1f; (What is this?) This session is part of a learning curriculum that I designed to incrementally skill up and empower a team of Designers and Researchers whose skillset and ways of working needed to evolve to keep up with changes …

ASP.NET 文件上傳于下載

本文主要介紹一下&#xff0c;在APS.NET中文件的簡單上傳于下載&#xff0c;上傳是將文件上傳到服務器的指定目錄下&#xff0c;下載是從存入數據庫中的路徑&#xff0c;從服務器上下載。 1.上傳文件 (1)頁面代碼 <table align"center" cellpadding"0" …