Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Detecting remote host disconnection

Tags:

php

sockets

According to the documentation, socket_read() is supposed to return FALSE when the remote host has closed the connection, and an empty string '' when there is no more data to read. However, during my testing, it never returns FALSE, even when I close the remote host connection. Here is the relevant code:

$data = '';

do {
    $read = socket_read($socket, 1024);

    if ($read === FALSE) {
        throw new SocketDisconnectException();
    }

    $data .= $read;
} while ($read !== '');

The SocketDisconnectException never gets thrown, even when I disconnect the remote host connection. I've double and triple checked that I'm not catching the exception and discarding it, and even thrown in an echo and exit into the conditional as a sanity check.

Has the behavior of this function changed, or am I doing something wrong?

like image 348
FtDRbwLXw6 Avatar asked Jan 31 '12 19:01

FtDRbwLXw6


1 Answers

There seems to be a bug where if you're using PHP_NORMAL_READ it will return false on remote disconnect, but PHP_BINARY_READ will return "". PHP_BINARY_READ is the default, I'd suggest trying PHP_NORMAL_READ if that works for your purposes.

like image 60
TheOx Avatar answered Oct 02 '22 19:10

TheOx