Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect User Abort / Client Disconnection in PHP [closed]

Tags:

php

Recently we had the need to detect when a client aborted/disconnected abruptly from a server. By abruptly I mean not necessarily through the STOP button of a browser, actually, the client was a SOAP message sent through POST (using soapUI), hence, the disconnection could be as simple as stopping (Ctrl + C) the cliente before it recieved a response. We spent days trying to find a solution, until we found out how. So, this perhaps could be a question with an implicit response, but the goal is to provide information that can help many other people out there with the same need.

Here is the basic code we used our server in order to detect the client's disconnection:

<?PHP
ignore_user_abort(true);            // Continue running the script even when the client aborts/disconnects

sleep(5);                           // Sleep 5 seconds so we can stop the client before it recieves a reponse from the server

echo "RESPONSE sent to the client"; // Response to the Request
ob_flush();                         // Clean output buffer
flush();                            // Clean PHP's output buffer
usleep(500000);                     // Sleep half a second in order to detect if Apache's server sent the Response
echo " ";                           // Echo a blank space to see if it could be sent to the client
ob_flush();                         // Clean output buffer
flush();                            // Clean PHP's output buffer

if(connection_status() != 0) {      // Client aborted/disconnected abruptly
  return -1;
}
else {                              // Client recieved the response correctly
  return 0;
}

?>
like image 373
Norberto Soriano Avatar asked May 08 '12 19:05

Norberto Soriano


1 Answers

The "connection_aborted" function in PHP will solve your problem.

You can see the function syntax with example usages in this link.

like image 155
Jirilmon Avatar answered Oct 23 '22 11:10

Jirilmon