Executing PHP After Response Dispatch
A PHP script often encounters the need to process data further after responding to a server request. One such scenario involves handling incoming message parameters ("ID_OF_MESSAGE" and "TEXT_OF_MESSAGE") and generating a response with "ANSWER_TO_ID" and "RESPONSE_MESSAGE" params.
However, sending an HTTP 200 response to the server will immediately mark the message as delivered on the server-side. This presents a dilemma as immediate response generation is essential.
To overcome this, you can:
ignore_user_abort(true); //optional set_time_limit(0); ob_start(); // Handle initial processing 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 processing after request dispatch die(); // Ensure script termination
By setting ignore_user_abort() and set_time_limit(0), the script can continue executing indefinitely. The ob_* functions send the response headers and body immediately. The die() statement terminates the script, which is necessary to prevent infinite execution when set_time_limit(0) is used.
This technique allows you to handle incoming requests, send responses, and continue processing your PHP script without waiting for the browser to receive the full response.
The above is the detailed content of How Can I Execute PHP Code After Sending an HTTP Response?. For more information, please follow other related articles on the PHP Chinese website!