ob_*系列函數(shù), 是操作PHP本身的輸出緩沖區(qū).
所以, ob_flush是刷新PHP自身的緩沖區(qū).
而flush, 嚴(yán)格來(lái)講, 這個(gè)只有在PHP做為apache的Module(handler或者filter)安裝的時(shí)候, 才有實(shí)際作用.
它是刷新WebServer(可以認(rèn)為特指apache)的緩沖區(qū).
在apache module的sapi下, flush會(huì)通過(guò)調(diào)用sapi_module的flush成員函數(shù)指針,
間接的調(diào)用apache的api: ap_rflush刷新apache的輸出緩沖區(qū), 當(dāng)然手冊(cè)中也說(shuō)了, 有一些apache的其他模塊,
可能會(huì)改變這個(gè)動(dòng)作的結(jié)果..
有些Apache的模塊,比如mod_gzip,可能自己進(jìn)行輸出緩存,這將導(dǎo)致flush()函數(shù)產(chǎn)生的結(jié)果不會(huì)立即被發(fā)送到客戶端瀏覽器。
甚至瀏覽器也會(huì)在顯示之前,緩存接收到的內(nèi)容。例如 Netscape瀏覽器會(huì)在接受到換行或 html標(biāo)記的開(kāi)頭之前緩存內(nèi)容,并且在接受到 標(biāo)記之前,不會(huì)顯示出整個(gè)表格。
一些版本的 Microsoft Internet Explorer
只有當(dāng)接受到的256個(gè)字節(jié)以后才開(kāi)始顯示該頁(yè)面,所以必須發(fā)送一些額外的空格來(lái)讓這些瀏覽器顯示頁(yè)面內(nèi)容。
所以, 正確使用倆者的順序是. 先ob_flush, 然后flush,
當(dāng)然, 在其他sapi下, 不調(diào)用flush也可以, 只不過(guò)為了保證你代碼的可移植性, 建議配套使用.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?php // set_time_limit(0); header( 'Content-Type: text/event-stream' ); header( 'Cache-Control: no-cache' ); // ob_end_flush(); // ini_set('output_buffering', 0); // ini_set('implicit_flush', 1); if (ob_get_level() == 0) ob_start(); echo str_repeat ( ' ' ,4096); $long = 60; while ( $long > 0) { $time = date ( 'r' ); echo "data: The server time is: {$time}\n\n" ; ob_flush(); flush (); //break; sleep(1); $long --; } // var source=new EventSource("http://localhost:18000/sse.php");source.onmessage=function(event){console.info(event.data)}; ?> |
如果要在 nginx + fpm + php 上支持需要加一個(gè)響應(yīng)頭
header('X-Accel-Buffering: no');
This eliminates both proxy_buffering and (if you have nginx >= 1.5.6), fastcgi_buffering. The fastcgi bit is crucial if you're using php-fpm. The header is also far more convenient to do on an as-needed basis.
Docs on X-Accel-Buffering http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_buffering ;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?php // set_time_limit(0); header( 'Content-Type: text/event-stream' ); header( 'Cache-Control: no-cache' ); header( 'X-Accel-Buffering: no' ); // ob_end_flush(); // ini_set('output_buffering', 0); // ini_set('implicit_flush', 1); // if (ob_get_level() == 0) ob_start(); // echo str_repeat(' ' ,4096); $long = 60; while ( $long > 0) { $time = date ( 'r' ); echo "data: The server time is: {$time}\n\n" ; ob_flush(); flush (); //break; sleep(1); $long --; } // var source=new EventSource("http://localhost:18000/sse.php");source.onmessage=function(event){console.info(event.data)}; ?> |