php flush()函數使用注意事項

來源:互聯網
上載者:User
ob_flush/flush在手冊中的描述, 都是重新整理輸出緩衝區, 並且還需要配套使用, 所以會導致很多人迷惑…其實, 他們倆的操作對象不同, 有些情況下, flush根本不做什麼事情

ob_*系列函數, 是操作PHP本身的輸出緩衝區.

所以, ob_flush是重新整理PHP自身的緩衝區.

而flush, 嚴格來講, 這個只有在PHP做為apache的Module(handler或者filter)安裝的時候, 才有實際作用.
它是重新整理WebServer(可以認為特指apache)的緩衝區.

在apache module的sapi下, flush會通過調用sapi_module的flush成員函數指標,
間接的調用apache的api: ap_rflush重新整理apache的輸出緩衝區, 當然手冊中也說了, 有一些apache的其他模組,
可能會改變這個動作的結果..

有些Apache的模組,比如mod_gzip,可能自己進行輸出緩衝,這將導致flush()函數產生的結果不會立即被發送到用戶端瀏覽器。

甚至瀏覽器也會在顯示之前,緩衝接收到的內容。例如 Netscape瀏覽器會在接受到換行或 html標記的開頭之前緩衝內容,並且在接受到 標記之前,不會顯示出整個表格。

一些版本的 Microsoft Internet Explorer
只有當接受到的256個位元組以後才開始顯示該頁面,所以必鬚髮送一些額外的空格來讓這些瀏覽器顯示頁面內容。

所以, 正確使用倆者的順序是. 先ob_flush, 然後flush,

當然, 在其他sapi下, 不調用flush也可以, 只不過為了保證你代碼的可移植性, 建議配套使用.

<?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 上支援需要加一個回應標頭

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 ;

<?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)};?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.