How to Deal With Connection Aborted in PHP
Many PHP scripts produce output destined for some client somewhere, usually a web browser. If the web browser closes during the processing or there's a disconnect somewhere, then the PHP script has a problem to deal with. In the worst case, this can lead to an infinite loop consuming available server resources and potentially leaving a security hole for malicious actors to exploit in denial of service attacks.
One solution is to use the register_shutdown_function function to specify a shutdown function that will be executed at the end of the script. But this function isn't foolproof as shutdown functions execute irrespective of whether there has been a timeout or not, and in fact this can cause the script to run forever even after the browser has closed.
Another option is to detect if the client has disconnected using the php function connection_aborted. This function does what it says on the tin, it returns 1 if the client has disconnected and 0 if not.
This article was originally published in Hacking with PHP in April 2014. It has been fully updated for PHP 7 and is now also available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today.
Learn how to write efficient code with the official course from O'Reilly: Hacking with PHP.
Learn about key PHP features such as object orientation, caching, and security in this fast-paced video series from the experts at O'Reilly.
Become an expert in PHP and build websites of your own with the O'Reilly PHP curriculum.