Distinguish PHP stream_select Timeouts from Readable Streams

Last updated: November 26, 2026.

Use a strict comparison when checking stream_select(). A return of 0 means no stream became ready before the wait expired, while false means the call failed. A positive count means you can inspect the filtered arrays for ready streams.

<?php
function readWhenReady($socket): ?string
{
    $read = [$socket];
    $write = $except = null;
    $ready = stream_select($read, $write, $except, 0, 200000);

    if ($ready === false) {
        throw new RuntimeException('Stream selection failed');
    }
    if ($ready === 0) {
        return null;
    }

    $chunk = fread($read[0], 4096);
    if ($chunk === false) {
        throw new RuntimeException('Read failed');
    }
    return $chunk;
}

Rebuild the arrays before the next wait

The function replaces each array with only its ready members. If you reuse the filtered array after a timeout, it can be empty. Build a fresh list of the streams you still care about before you wait again. Pass variables for the read, write and exception sets because the function receives them by reference.

The example waits up to 200 milliseconds for one connected socket and then reads one chunk. Use a nonblocking socket in an event loop. A ready socket can yield an empty read at EOF. Check feof() and remove a closed stream from your watch list. A nonempty chunk can still be only part of a message, so buffer data until your protocol has a complete frame.

Use a bounded wait and test the stream type

A zero-second, zero-microsecond timeout is for polling when the caller has other work to do. In an otherwise idle loop, use a positive timeout to avoid spinning. If your operation has a total deadline, calculate the remaining time between calls. Repeating a 200-millisecond timeout can otherwise keep the operation alive indefinitely.

Check the exact PHP build and OS before using the same loop for pipes from proc_open(). The PHP issue tracker documents Windows pipe behavior that differs from socket behavior. Verify that stream type separately or use a process library which handles Windows pipes explicitly.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov