Is it possible to close the output stream of a PHP script? I have a script which needs to do some post processing, but during and after the post processing it won’t send any data to the client anymore, so I’d like to close the connection before the post processing.
Edit: In my application I have a cache which needs to be rebuild every now and then. However, I don’t want to slow a user down. What I want is to determine at the end of the script if the cache needs to be rebuild. So I want to close the output stream first, so the user gets it’s data, and then I want to rebuild the cache. It isn’t really critical to do this, but I think it’s better to close the connection first, so the user won’t notice that the cache is being rebuild if that takes a long time.
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:
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:
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.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.