Detect User Abort / Client Disconnection in PHP
<p>Recently we had the need to detect when a <strong>client</strong> aborted/disconnected abruptly from a <strong>server</strong>. By abruptly I mean not necessarily through the <strong><em>STOP</em></strong> button of a browser, actually, the client was a SOAP message sent through POST (using <strong><em>soapUI</em></strong>), hence, the disconnection could be as simple as stopping (<strong><em>Ctrl + C</em></strong>) 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.</p>

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

<pre><code>&lt;?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;
}

?&gt;
</code></pre>
