Home > Article > Backend Development > PHP executes time-consuming scripts and outputs content in real time
We sometimes have such a requirement. When executing a time-consuming script, the data will be output only after the script is executed. If it is not processed, it will cache the content output to the page into the memory until it is processed. It will be executed later. Here, we need real-time output.
flush — Flush the output buffer
Flushes the buffer of the PHP program, regardless of the circumstances under which PHP is executed (CGI, web server, etc.). This function sends all the program's output so far to the user's browser.
Theflush() function has no effect on the cache mode of the server or client browser. Therefore, both the ob_flush() and flush() functions must be used to flush the output buffer.
Individual web server programs, especially web server programs under Win32, will still cache the output of the script until the end of the program before sending the results to the browser.
Some Apache modules, such as mod_gzip, may perform output caching themselves, which will cause the results generated by the flush() function to not be sent to the client browser immediately.
Even the browser will cache the received content before displaying it. For example, the Netscape browser caches content until it receives a line break or the beginning of an html tag, and does not display the entire table until it receives a f16b1740fad44fb09bfe928bcc527e08 tag.
Some versions of Microsoft Internet Explorer will only begin to display the page after receiving 256 bytes, so some additional spaces must be sent to allow these browsers to display the page content.
If real-time output is required, two core functions ob_flush, flush;
<?php // echo phpinfo(); if (ob_get_level() == 0) ob_start(); for ($i = 0; $i<10; $i++){ echo "<br> Line to show."; echo str_pad('',4096)."\n"; ob_flush(); flush(); sleep(2); } echo "Done."; ob_end_flush();
Recommended: "PHP Video Tutorial"
The above is the detailed content of PHP executes time-consuming scripts and outputs content in real time. For more information, please follow other related articles on the PHP Chinese website!