How can PHP be used for long file processing tasks while maintaining real-time status updates?

When dealing with long file processing tasks in PHP while needing to provide real-time status updates, one approach is to use AJAX requests to periodically check the status of the task and update the user interface accordingly. By breaking down the processing task into smaller chunks and updating the status after each chunk is completed, users can see the progress in real-time without the need for continuous page refreshes.

// PHP code snippet for long file processing with real-time status updates

// Start the long file processing task
$start = microtime(true);

// Simulate a long file processing task
$totalChunks = 10;
for ($i = 1; $i <= $totalChunks; $i++) {
    // Process a chunk of the file
    usleep(500000); // Simulate processing time
    
    // Update the status
    $progress = round(($i / $totalChunks) * 100);
    echo json_encode(['progress' => $progress]) . PHP_EOL;
    ob_flush();
    flush();
}

// Task completed
$end = microtime(true);
$totalTime = $end - $start;
echo json_encode(['progress' => 100, 'message' => 'Task completed in ' . $totalTime . ' seconds.']) . PHP_EOL;