When you run PHP scripts in the console, all the standard output text from that script shows up in the cons开发者_开发知识库ole window while the script is running. Is it possible for a browser window to similarly receive status reports in the browser while a lengthy PHP script is running, instead of getting all the output dumped at the conclusion of the script?
Yes. Just call flush() and ob_flush() periodically. It's important to write some output at least every 120 seconds to keep the connection to the browser alive.
A rough example:
while(!$done) {
//doWork();
echo number_format(100 * ($workDone/$workTotal)) . "% ";
flush();
ob_flush();
}
Edit: here's an arbitrary proof of concept that works in my env:
print('hello');
print(str_repeat(".\n", 2048));
flush();
//this might be a safe way to only flush the buffer if necessary?
if(ob_get_length())
ob_flush();
sleep(60);
Yes, one thing you'll need to worry about if you have a particularly long execution time is timing out. This can occur as a PHP timeout or as a browser timeout (generally about 2 minutes).
This PHP documentation about connection handling has quite a bit of good information about keeping connections alive.
精彩评论