Skip to content
PHP Logo

How can PHP flush() and sleep() functions be effectively used in conjunction for managing user interactions and server responses during time-based operations?

When dealing with time-based operations in PHP, it's important to manage user interactions and server responses effectively. One way to do this is by using the `flush()` and `sleep()` functions in conjunction. By periodically flushing the output buffer with `flush()` and introducing delays with `sleep()`, you can control the timing of server responses and ensure a smooth user experience during time-consuming operations.

php
// Start output buffering
ob_start();

// Perform time-based operations
for ($i = 1; $i <= 10; $i++) {
    // Output progress to the user
    echo "Processing step $i...<br>";
    
    // Flush output buffer
    flush();
    
    // Introduce a delay to simulate processing time
    sleep(1);
}

// End output buffering
ob_end_flush();