Aborting Connections In PHP

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.

ignore_user_abort(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 will not work:


if (connection_aborted()==1) {
  fwrite($filehandle, 'aborted!');
}

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).


if (connection_aborted()) {
  fwrite($filehandle, 'aborted!');
}

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 15 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.