Stream_select()

The function stream_select() waits for a socket to become readable. It also allows a timeout, so it can be used for our purposes. The interface to stream_select() is somewhat strange: it modifies its arguments so that the arrays contain just the streams on which something happened.

$write = $error = array();
$read = array($socket);
stream_select($read, $write, $error, 4);
if (in_array($socket, $read))
{
    while ($data = fread($socket, 2000))
    {
        echo $data;
    }
}
else
{
    echo "Read timeout\n";
}

The function stream_select() waits until one of the streams becomes readable, or the timeout has expired. Stream_select() will block for at most 4 seconds. If the timeout expired, the socket resource will not be in the $read array. If the socket became readable, the resource is in $read.

Note that this example only introduces a read timeout on the first read. If the remote server sends some bytes and then stalls, stream_select() will consider the stream readable, but the read will still block.