This function pauses the script for the specified number of seconds and nanoseconds. It has higher accuracy than sleep and usleep , and is suitable for scenarios where finer latency control is required.
ob_flush()
Force the output buffer content of PHP to the browser, but does not close the buffer. When used with flush() , the content can be "pushed" in real time.
Note: In order to ensure that the output actually reaches the browser, it is usually used with flush() , and caching and compression cannot be disabled on both the server and browser side.
<?php
// Close script execution time limit(As needed)
// set_time_limit(0);
// Turn on output buffering
ob_start();
// Disable browser caching and compression,Ensure instant data transmission
header("Content-Type: text/plain");
header("Cache-Control: no-cache");
header("X-Accel-Buffering: no"); // for Nginx Disable cache
// closure gzip compression(If the server is turned on by default)
// Specific methods are configured according to the server environment
for ($i = 1; $i <= 5; $i++) {
echo "Current steps:{$i}\n";
// Force refresh PHP Output buffer
ob_flush();
flush();
// use time_nanosleep Microsecond delay,0.5Second = 500,000,000 纳Second
time_nanosleep(0, 500000000);
}
echo "All steps are completed!\n";
?>
ob_start() : Start the output buffering to ensure that buffer flushing can be controlled.
echo : output information one by one.
ob_flush() + flush() : Force the buffer content to be sent to the client and refresh the browser display.
time_nanosleep(0, 500000000) : Pause for 0.5 seconds (500,000,000 nanoseconds), making the output effect more obvious and simulating real-time processes.
Set up HTTP headers appropriately to avoid content lag caused by browser and server cache.
Server configuration impact <br> Servers (such as Apache, Nginx) may enable output compression or buffering by default, which will affect the real-time output effect. Make sure to turn off gzip compression and speed up cache.
Browser behavior <br> Some browsers accumulate content until it reaches a certain size, and may not be displayed immediately if the output content is too small. You can try to output a certain number of whitespace characters to trigger rendering.
Buffer size
Both the output buffer of PHP and the size of the Web server buffer affect the output speed. The buffer size can be adjusted according to actual conditions.
PHP Version
time_nanosleep is supported starting with PHP 5.0.0 to ensure that your environment meets the requirements.
By combining time_nanosleep and ob_flush() , we can implement step-by-step and segmented real-time data output in PHP, enhancing users' perception of the progress of long-term scripts. This method is simple and easy to use and is suitable for scenarios where delays require microseconds.
If combined with reasonable server and browser settings, you can obtain very smooth real-time output effects and improve the user experience.