首頁  >  文章  >  後端開發  >  PHP中output buffering的原理及應用

PHP中output buffering的原理及應用

藏色散人
藏色散人轉載
2019-10-22 13:43:071921瀏覽

php快取過程

在請求一個PHP的過程中,實際上經過三個快取:

1.程式快取

2 .ob快取

3.瀏覽器快取.

開啟ob的兩個方法

1.在php.ini 設定;output_buffering = 4096這裡去掉;號碼即可

2 在php頁面中使用ob_start();

透過php.ini 開啟的,則作用於所有的php頁面。使用ob_start()開啟則只作用於該頁面

ob快取的知識點

在服務中,如果我們開啟了ob緩存,則echo資料先放入到ob中

當PHP頁面執行到最後,則會把ob緩存的資料(如果有的話), 強制刷新到程式緩存,然後透過apache對資料封裝成http回應包,傳回給瀏覽器

如果沒有ob,所有的資料直接放入程式快取。 header資訊不管你是否開啟ob,總是放入到程式快取。

ob相關的函數

ob_start($callback)

//在当前页面中开启ob,注意callback
ob_start($callback);

ob_get_contents()

//获取当前ob缓存中的内容
ob_get_contents()

ob_get_clean()

//获取当前ob缓存中的内容,并且清空当前的ob缓存
ob_get_clean()

ob_flush()

//将ob缓存中的内容,刷到程序缓存中,但并没有关闭ob缓存
ob_flush()

ob_end_flush()

//关闭ob缓存,并将数据刷回到程序缓存中
ob_end_flush()

ob_clean()

//将ob缓存中的内容清空
ob_clean()

ob_end_clean()

//将ob缓存中的数据清空,并且关闭ob缓存
ob_end_clean()

注意ob_start($callback)的回呼

<?php
ob_start("callback_func");
function callback_func($str){
    return "callback".$str;
}
echo "123";//输出:callback123

應用場景

在header()發送之前的報錯

出錯程式碼

<?php
echo "before_header";
header("Content-type:text/html;charset=utf-8");
echo "after_header";

輸出:

Warning: Cannot modify header information - headers already sent by (output started at /Users/shuchao/Desktop/test.php:2) in /Users/shuchao/Desktop/test.php on line 3

解決辦法

在發送header前開啟ob,則所有的echo內容都會到ob裡面,從而解決錯誤。

<?php
ob_start();
echo "before_header\n";
header("Content-type:text/html;charset=utf-8");
echo "after_header\n";

輸出

before_header
after_header

以上是PHP中output buffering的原理及應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除