Continuing PHP Execution After Sending Response
In a scenario where a PHP script receives an incoming message, processes it, and sends a response to the requesting server, there is a need to continue PHP script execution after sending the initial response. This becomes challenging as the server typically marks the message as delivered upon receiving an HTTP 200 response.
Avoiding Database Storage and Cron Jobs
Instead of resorting to storing messages in a database and relying on a cron job, there is a more immediate solution. This involves sending the HTTP 200 response and then continuing PHP script execution.
PHP Script Implementation
To implement this solution, follow these steps in your PHP script:
ignore_user_abort(true); // Not required but can prevent premature termination set_time_limit(0); ob_start(); // Perform initial processing here echo $response; // Send the response header('Connection: close'); header('Content-Length: '.ob_get_length()); ob_end_flush(); @ob_flush(); flush(); fastcgi_finish_request(); // Required for PHP-FPM (PHP > 5.3.3) // Continue script execution // ... die(); // End the script especially when set_time_limit=0 is used and the task is complete
This code sequence allows the script to send the response, but the PHP process continues to run. You can perform additional processing, tasks, or send another response if necessary. It's important to call die() at the end to terminate the script and free up resources.
The above is the detailed content of How Can I Continue PHP Script Execution After Sending an HTTP Response?. For more information, please follow other related articles on the PHP Chinese website!