What are the implications of long download times on progress bars implemented in PHP scripts?

Long download times can cause progress bars implemented in PHP scripts to appear stuck or unresponsive, leading to a poor user experience. One way to address this issue is to use AJAX to periodically update the progress bar based on the actual progress of the download.

// PHP script to update progress bar using AJAX

// Start the download process
// For demonstration purposes, we will simulate a long download time
$totalSize = 1000000; // Total file size
$downloaded = 0; // Amount downloaded so far

while ($downloaded < $totalSize) {
    // Simulate downloading a chunk of data
    $chunkSize = 1000;
    $downloaded += $chunkSize;

    // Calculate the progress percentage
    $progress = min(100, round(($downloaded / $totalSize) * 100));

    // Output the progress as JSON
    echo json_encode(['progress' => $progress]);

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

    // Simulate a delay to mimic a slow download
    usleep(50000); // 50 milliseconds
}