Detecting user disconnection / client disconnection in PHP

Recently, we needed to detect when a client is interrupted / disconnected suddenly from the server . By the way, it is not necessary through the STOP button of the browser, in fact, the client was a SOAP message sent through POST (using soapUI ), therefore, disconnecting can be as simple as stopping ( Ctrl + C ) the client before it receives answer. We spent days trying to find a solution until we figured out how to do it. Thus, perhaps this may be a question with an implicit answer, but the goal is to provide information that can help many other people with the same need.

Here is the basic code that we used our server to detect client 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 output buffer usleep(500000); // Sleep half a second in order to detect if Apache 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 output buffer if(connection_status() != 0) { // Client aborted/disconnected abruptly return -1; } else { // Client recieved the response correctly return 0; } ?> 
+7
source share
1 answer

The connection_aborted "function in PHP will solve your problem.

You can see the syntax of the function with usage examples in this link .

+1
source

All Articles