標籤:
我的本地環境 windows + apche + php5.2
今天,碰到一個詭異的問題,以前認為 php 指令碼中調用 heade()函數之前不能有任何的如 echo,print ,print_r,var_dump等輸出,否則的話就會報錯。
但是,
<?phpheader( ‘Expires: Mon, 26 Jul 1998 05:00:00 GMT‘ );echo "Expires: Mon, 26 Jul 1998 05:00:00 ;";header( ‘Expires: Mon, 26 Jul 1978 05:00:00 GMT‘ );
想上面這樣,瀏覽器訪問,執行指令碼,沒有報錯。(本以為彙報這樣的錯誤:Warning: Cannot modify header information - headers already sent by)
此事何解:???
方法:
開啟瀏覽器的偵錯主控台,發現 HTTP response header 中的Exipres 為 1978,頓時明白了。
聯想到php 的輸出緩衝的問題,在php 的設定檔中,有這麼一段,看最後一句
; Output buffering is a mechanism for controlling how much output data; (excluding headers and cookies) PHP should keep internally before pushing that; data to the client. If your application‘s output exceeds this setting, PHP; will send that data in chunks of roughly the size you specify.; Turning on this setting and managing its maximum buffer size can yield some; interesting side-effects depending on your application and web server.; You may be able to send headers and cookies after you‘ve already sent output; through print or echo. You also may see performance benefits if your server is; emitting less packets due to buffered output versus PHP streaming the output; as it gets it. On production servers, 4096 bytes is a good setting for performance; reasons.; Note: Output buffering can also be controlled via Output Buffering Control; functions.; Possible Values:; On = Enabled and buffer is unlimited. (Use with caution); Off = Disabled; Integer = Enables the buffer and sets its maximum size in bytes.; Note: This directive is hardcoded to Off for the CLI SAPI; Default Value: Off; Development Value: 4096; Production Value: 4096; http://php.net/output-buffering
output_buffering = 4096
4K位元組的緩衝,這意味著 前面的這兩個輸出
header( ‘Expires: Mon, 26 Jul 1998 05:00:00 GMT‘ );echo "Expires: Mon, 26 Jul 1998 05:00:00 ;";
還緩衝在伺服器中(我的是apache伺服器,nginx伺服器有是怎麼樣子呢,這個還不知道。。。),還沒有通過http輸出到瀏覽器,因此,後面的
header( ‘Expires: Mon, 26 Jul 1978 05:00:00 GMT‘ );這個輸出呢,就把緩衝區中的 回應標頭修改為了 1978。
另外:
1、如果輸出達到 4096(4k)位元組時,伺服器會立即將緩衝區中的內容 flush 出來,即立即輸出給瀏覽器。
2、關於緩衝區處理的一些列函數,php提供了 ob_flush(), ob_get_contents()等一系列函數
還有一點:當我們不確定 緩衝區中的內容是否已經有輸出,那怎麼辦呢?
php 內建的函數 headers_sent() 可以用來判斷,一些架構 如cakephp中就是這個來檢查的!!
if (!headers_sent()) {
header( ‘Expires: Mon, 26 Jul 1978 05:00:00 GMT‘ );
}
這樣就可以了,就確保不會報這樣子的錯 Warning: Cannot modify header information - headers already sent by
詭異的php 輸出緩衝