For twenty years, PHP developers who wanted to watch many sockets at once had one built-in tool: stream_select(). It works, but it’s based on the select() system call, which is slow with many connections and typically limited to 1,024 file descriptors. PHP 8.6, released on 19 November 2026, adds a new Polling API under the Io\Poll namespace. It automatically uses the best mechanism on each platform: epoll on Linux, kqueue on BSD and macOS, event ports on Solaris/illumos, WSAPoll on Windows, and plain poll elsewhere.

This tutorial builds a small non-blocking TCP echo server with the new API, then covers timeouts, write readiness, one-shot and edge-triggered modes, and error handling. Sources: the PHP 8.6 release page and the Polling API RFC.

What the API is (and isn’t)

The RFC is clear that this is a polling primitive, not an event loop. You get “tell me which of these streams are ready”. You don’t get timers, signals or child-process management. Libraries like ReactPHP and AMPHP can build on it as a single, efficient backend. For your own code, it’s a direct, scalable replacement for stream_select().

The main pieces:

Class / enum Purpose
Io\Poll\Context Holds the watchers and has the wait() method
Io\Poll\Watcher One registered handle plus the events it watches
StreamPollHandle Wraps a PHP stream resource so it can be polled
Io\Poll\Event Enum: Read, Write, Error, HangUp, ReadHangUp, OneShot, EdgeTriggered
Io\Poll\Backend Enum: Auto, Poll, Epoll, Kqueue, EventPorts, WSAPoll

StreamPollHandle is a global class that implements the Io\Poll\Handle marker interface. Only internal classes can implement that interface; a userland class that tries gets a fatal error.

Before: the stream_select() version

<?php
$server = stream_socket_server('tcp://0.0.0.0:8080');
$clients = [];

while (true) {
    $read = [$server, ...$clients];
    $write = $except = null;
    stream_select($read, $write, $except, null);
    // ...accept new clients or echo data back
}

Every loop rebuilds the array and the kernel scans every descriptor. That’s the O(n) cost the RFC wants to remove.

After: an echo server with Io\Poll

<?php
use Io\Poll\{Context, Event};

$server = stream_socket_server('tcp://0.0.0.0:8080', $errno, $errstr);
if (!$server) {
    exit("Failed to create server: $errstr\n");
}
stream_set_blocking($server, false);

$poll = new Context();               // Backend::Auto by default
echo "Using backend: {$poll->getBackend()->name}\n";

$poll->add(new StreamPollHandle($server), [Event::Read], ['type' => 'server']);

while (true) {
    foreach ($poll->wait() as $watcher) {
        $stream = $watcher->getHandle()->getStream();
        $data   = $watcher->getData();

        if ($data['type'] === 'server') {
            $client = stream_socket_accept($server, 0);
            if ($client) {
                stream_set_blocking($client, false);
                $poll->add(new StreamPollHandle($client), [Event::Read], ['type' => 'client']);
            }
            continue;
        }

        if ($watcher->hasTriggered(Event::HangUp) || $watcher->hasTriggered(Event::Error)) {
            $watcher->remove();
            fclose($stream);
            continue;
        }

        $chunk = fread($stream, 8192);
        if ($chunk === '' || $chunk === false) {
            $watcher->remove();
            fclose($stream);
        } else {
            fwrite($stream, $chunk);
        }
    }
}

Run it with php server.php and test with nc localhost 8080. Open a few terminals; each connection gets its own watcher.

Key points:

  • add() returns a Watcher. The third argument is any user data you want back later via getData(). That replaces the “search the array to find out which client this is” pattern.
  • wait() returns only the watchers that fired. No rebuilding arrays.
  • Error and HangUp are always monitored. You don’t request them; they just show up in getTriggeredEvents() / hasTriggered().
  • Remove before you close. Call $watcher->remove() and then fclose(). A removed watcher becomes inactive and can’t be reused.

Timeouts

wait() takes three optional arguments:

public function wait(
    ?int $timeoutSeconds = null,
    int $timeoutMicroseconds = 0,
    ?int $maxEvents = null
): array
  • null seconds waits indefinitely.
  • 0 seconds and 0 microseconds returns immediately (a non-blocking check).
  • Microsecond values of 1,000,000 or more are allowed; the overflow carries into seconds, just like stream_select().
  • $maxEvents caps how many watchers come back from one call.

A loop that also does periodic housekeeping:

$lastTick = hrtime(true);

while (true) {
    foreach ($poll->wait(0, 250_000) as $watcher) {   // 250 ms
        handle($watcher);
    }
    if (hrtime(true) - $lastTick > 5_000_000_000) {    // every ~5 s
        closeIdleClients();
        $lastTick = hrtime(true);
    }
}

Waiting for write readiness

Writing a large response to a slow client can fill the socket buffer. Instead of blocking, buffer the data and ask to be told when the socket is writable again with modifyEvents():

$pending = [];  // spl_object_id($watcher) => string

function queueWrite(\Io\Poll\Watcher $w, string $bytes, array &$pending): void {
    $pending[spl_object_id($w)] = ($pending[spl_object_id($w)] ?? '') . $bytes;
    $w->modifyEvents([Event::Read, Event::Write]);
}

// inside the loop
if ($watcher->hasTriggered(Event::Write)) {
    $id = spl_object_id($watcher);
    $written = fwrite($stream, $pending[$id]);
    $pending[$id] = substr($pending[$id], (int) $written);
    if ($pending[$id] === '') {
        unset($pending[$id]);
        $watcher->modifyEvents([Event::Read]);  // stop watching for Write
    }
}

modify() changes events and user data together, modifyEvents() only events, and modifyData() only data.

One-shot and edge-triggered modes

Two input-only flags change how a watcher behaves:

  • Event::OneShot removes the watcher automatically after it triggers once. Useful for “tell me when this upstream connection is ready, once”.
  • Event::EdgeTriggered reports state changes rather than state. It’s supported only on epoll and kqueue, and with it you must read until the stream is empty each time, or you won’t be woken again.

Check support before relying on edge triggering:

use Io\Poll\Backend;

$backend = (new Context())->getBackend();
var_dump($backend->supportsEdgeTriggering());
print_r(Backend::getAvailableBackends());

Event::ReadHangUp (peer shut down its write half) is Linux epoll only and must be requested explicitly.

Choosing a backend explicitly

Backend::Auto is the right default. For tests, you can force a backend. If it isn’t available on the platform, the constructor throws Io\Poll\BackendUnavailableException:

use Io\Poll\{Backend, Context, BackendUnavailableException};

try {
    $poll = new Context(Backend::Epoll);
} catch (BackendUnavailableException) {
    $poll = new Context(Backend::Poll);
}

Error handling

All poll exceptions extend Io\Poll\PollException, which extends Io\IoException. The ones you’ll most often see:

  • InvalidHandleException – the stream isn’t valid for polling.
  • HandleAlreadyWatchedException – you added the same handle twice.
  • InactiveWatcherException – you used a watcher after remove() (or after a one-shot fired).
  • FailedPollWaitException – the underlying wait failed. Failure exceptions carry error-code constants such as ERROR_INTERRUPTED.

Should you use it?

  • Writing a long-running socket server, worker or proxy in plain PHP? Yes. This is the scalable replacement for stream_select().
  • Using ReactPHP, AMPHP or Revolt? Keep using them. They’re the intended consumers of this API and can adopt it as a backend.
  • Typical PHP-FPM web app? You probably won’t touch it directly.

Also remember that PHP 8.6.0 shipped alongside security releases for older branches (8.2.36, 8.3.37, 8.4.28 and 8.5.13). If you’re not ready for 8.6 yet, at least update within your branch.

Key takeaways

  • PHP 8.6’s Io\Poll API wraps epoll, kqueue, event ports, WSAPoll and poll behind one interface.
  • Wrap streams in StreamPollHandle, add them to a Context, and loop over wait().
  • Attach user data to watchers, use modifyEvents() for write readiness, and always remove() before fclose().
  • Read the RFC for the full class reference.