What is the recommended approach for displaying loading indicators or progress bars in PHP scripts?

When running time-consuming tasks in PHP scripts, it is recommended to display loading indicators or progress bars to keep users informed about the progress of the operation. This can be achieved by using AJAX requests to periodically update the status of the task and display it to the user in real-time.

<?php
// Start the time-consuming task
$start = time();

// Loop through the task and update progress
for ($i = 0; $i < 100; $i++) {
    // Simulate some processing time
    usleep(50000);

    // Calculate progress percentage
    $progress = round(($i / 100) * 100);

    // Send progress to the client
    echo json_encode(['progress' => $progress]);

    // Flush the output buffer to send the progress to the client immediately
    ob_flush();
    flush();
}

// End the task
$end = time();

// Calculate total time taken
$totalTime = $end - $start;

// Send completion message to the client
echo json_encode(['message' => 'Task completed in ' . $totalTime . ' seconds']);

// Flush the output buffer
ob_end_flush();
?>