Home > Backend Development > PHP Tutorial > How Can I Execute PHP Code After Sending an HTTP Response?

How Can I Execute PHP Code After Sending an HTTP Response?

Susan Sarandon
Release: 2024-12-30 22:19:11
Original
703 people have browsed it

How Can I Execute PHP Code After Sending an HTTP Response?

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template