UPDATE
The way to handle this case is a combination of output buffering and the appropriate HTTP headers.
From the HTTP/1.1 Specification Section 14.10:
HTTP/1.1 defines the "close" connection option for the sender to
signal that the connection will be closed after completion of the
response.
So, if we pass along an HTTP Content-Length header in addition to Connection: close, the browser knows to close the connection after the specified response length is received:
- Buffer ALL the script output so that you retain the capability to send headers
- Once you have the full output data, send the appropriate headers to the client
- Continue your processing ... but don't try to send output or you'll receive errors because headers have been sent.
Also, be careful as you can run up against script execution time limits in web server SAPI if you do too much processing. Finally, you should tell PHP to ignore a "user abort" in this particular script using ignore_user_abort()
because the browser will close the connection as a result of what you're doing and you want PHP to continue processing.
<?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 might examine the PHP manual section on Connection handlingdocs.
Alternatively, why not start output buffering? Then you can capture all the output that would be sent then decide later if you actually want to do anything with it.
<?php
echo 'before output buffering';
ob_start();
echo 'after output buffering';
$output = ob_get_contents();
// script's only output to this point will be 'before output buffering'
// I changed my mind, send the output ...
ob_end_flush();
?>