UPDATE
The way to handle this case is a combination of output buffering and associated HTTP headers.
From the HTTP / 1.1 Specification Section 14.10 :
HTTP / 1.1 defines the "close" parameter for the sender to signal that the connection will be closed after the completion of the Response.
So, if we go through the HTTP Content-Length header in addition to Connection: close, the browser knows to close the connection after receiving the specified response length:
- The ALL script buffer prints so that you retain the ability to send headers
- Once you get the full output, send the appropriate headers to the client
- Continue processing ... but do not try to send the output or you will get errors because the headers are sent.
Also, be careful, as you may encounter script runtime limitations in the SAPI web server if you process too much. Finally, you must tell PHP to ignore the โuser interruptโ in this particular script using ignore_user_abort() , as the browser will close the connection as a result of what you are doing and you want PHP to continue to process.
<?php ignore_user_abort(); ob_start(); // do stuff, generate output // get size of the content $length = ob_get_length(); // tell client to close the connection after $length bytes received header('Connection: close'); header("Content-Length: $length"); // flush all output ob_end_flush(); ob_flush(); flush(); // close session if you have one ... // continue your processing tasks ... ?>
You can study the PHP manual section on Handling connection docs .
Alternatively, why not start output buffering? You can then capture all the output that will be sent, and then decide later if you really want to do anything with it.
<?php echo 'before output buffering'; ob_start(); echo 'after output buffering'; $output = ob_get_contents();
source share