Home > Article > Backend Development > How to Send HTTP Responses in PHP and Continue Execution for Long-Running Processes?
When faced with time-consuming operations that exceed web application timeouts, developers often seek solutions to continue PHP execution beyond the HTTP response delivery. In this particular case, the challenge is to enable PHP to transmit a complete HTTP response promptly while simultaneously initiating and completing database and email processing within a prescribed time frame of one minute.
The most straightforward method is utilizing ob_end_flush() and flush() functions strategically. By terminating the output buffering process and releasing the HTTP headers alongside the user-visible text, the script effectively signals the completion of the response to the client.
Here's an example code snippet that demonstrates this approach:
ob_end_clean(); header("Connection: close"); ignore_user_abort(); // Disable abort ob_start(); echo ('Success message for the user'); $size = ob_get_length(); header("Content-Length: $size"); ob_end_flush(); // Flush the initial content flush(); // Ensure proper flushing session_write_close(); // Delegate time-consuming tasks here sleep(30); echo('Tasks completed after 30 seconds');
With this approach, the script notifies the client of a successful operation and initiates subsequent time-consuming tasks without causing the application to time out.
The above is the detailed content of How to Send HTTP Responses in PHP and Continue Execution for Long-Running Processes?. For more information, please follow other related articles on the PHP Chinese website!