網頁上的 PHP 的程式通常是 全部執行完成後, 才會一起將資料於螢幕上呈現出來.
但是若程式要跑很久, 想要跑完一小段, 就先將那一小段的資料(Buffer)秀出來呢?
強迫 PHP 將 Buffer 的資料提前秀出
想達成上述的需求, 可以使用這個 PHP: flush
此文件有下述說明:
flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.
簡單講, 就是若要達成上述的需求, 需要 flush() + ob_flush() 搭配.
測試程式如下:
<?php header('Content-type: text/html; charset=utf-8'); $t = 0; $time = time() + 300; while (time() < $time) { if ($t < time()) { echo 'a'; ob_flush(); flush(); } $t = time(); } ?>
此程式看到 'a' 會一直印出來. 若將 ob_flush(), flush() 拿掉, 會等整個程式執行完後, 才會於頁面秀出來.
再看下面的範例:
<?php header('Content-type: text/html; charset=utf-8'); for ($i = 0; $i < 10; $i++) { echo $i . '<br>'; flush(); ob_flush(); sleep(1); } ?>