What is the recommended approach for handling script processing messages in PHP to ensure a smooth user experience?
When processing long-running scripts in PHP, it is essential to provide feedback to the user to ensure a smooth experience. One recommended approach is to use session variables to store progress messages and update them as the script runs. This allows users to see real-time updates on the processing status.
<?php
// Start the session
session_start();
// Set initial progress message
$_SESSION['progress_message'] = "Processing script...";
// Long-running script
for ($i = 0; $i < 100; $i++) {
// Update progress message
$_SESSION['progress_message'] = "Processing item $i...";
// Simulate processing time
usleep(50000); // 50ms
}
// Final progress message
$_SESSION['progress_message'] = "Script processing complete.";
// End the session
session_write_close();
?>