Aborting Connections In PHP

19th January 2008 - 2 minutes read time

Sometimes in PHP you will have to do some things that might take a little time. You will therefore have a little trouble with users closing the browser or moving to another page before the script has finished. In this case you will want to either continue to execute the script just shut it down depending on what the user has done.

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent. Use the flush() function after the echo call to force PHP to sent output information to the browser.

To run the script to the end no matter what the user has done use the ignore_user_abort() function with the parameter of true.

This might be useful if you are recording things to a database so that data integrity is still maintained.

To detect if a user has aborted the connection use the connection_aborted() function. Although the documentation on the PHP site says that the function returns an integer (1 if the client has disconnected, 0 otherwise) detecting the integer doesn't work reliably.

This code wll not work:

It is more reliable to assume that the function returns a boolean value as the 1 will be interpreted as true (disconnected) and the 0 as false (still connected).

Add new comment

The content of this field is kept private and will not be shown publicly.