Home > Article > Backend Development > How to Run PHP Operations After Sending an HTTP Response?
Executing PHP Operations Post HTTP Response Sending
In PHP 5.2, when running as mod_php, sending an HTTP response can interrupt long-running database requests and email processing. To address this issue, one can utilize a technique that allows PHP to send a complete HTTP response to the client and then continue executing operations for an additional duration.
The following snippet accomplishes this:
ob_end_clean(); header("Connection: close"); ignore_user_abort(); // optional ob_start(); echo ('Text the user will see'); $size = ob_get_length(); header("Content-Length: $size"); ob_end_flush(); // Strange behaviour, will not work flush(); // Unless both are called ! session_write_close(); // Added a line suggested in the comment // Do processing here sleep(30); echo('Text user will never see');
Upon execution, the script immediately sends a complete HTTP response to the client. It then commences processing the database requests and emails in the background, which can take up to a minute. Note that user interaction will be cut off once the response is sent.
The above is the detailed content of How to Run PHP Operations After Sending an HTTP Response?. For more information, please follow other related articles on the PHP Chinese website!