Handling multiple network connections efficiently is an important part of backend development. Applications such as chat servers, real-time notification systems, API gateways, and network services often need to manage several connections without waiting for each operation to finish.
Traditional blocking I/O can make this difficult because a process may spend considerable time waiting for data from one connection. PHP developers have used functions such as stream_select() to monitor multiple streams, but this approach has limitations when applications need to manage a large number of connections.
PHP 8.6 introduces a new I/O Polling API through the Io\Poll namespace. It provides a more structured way to monitor multiple streams and identify when they are ready for reading or writing.
The API uses operating system polling mechanisms such as epoll, kqueue, event ports, and WSAPoll, depending on platform availability. This makes it a useful foundation for building event loops and network applications.
In this article, we will understand non-blocking I/O, explore the new PHP 8.6 Polling API, and implement practical examples for handling multiple network connections.
What Is Non-Blocking I/O?
Non-blocking I/O is a programming approach in which an application does not wait indefinitely for a read or write operation to complete.
In traditional blocking I/O, a program waits until the requested operation can proceed.
For example, consider a server waiting for a client to send a message:
<?php
$client = stream_socket_accept($server);
$data = fread($client, 8192);
echo $data;
The fread() operation may block while waiting for incoming data. During that time, the application cannot continue executing the next operation in the same execution flow.
This becomes a problem when one process needs to handle multiple connections.
Non-blocking I/O changes this behavior:
<?php
stream_set_blocking($client, false);
$data = fread($client, 8192);
if ($data === false || $data === '') {
echo "No data available yet.";
} else {
echo $data;
}
With non-blocking mode enabled, the read operation returns without waiting for future data. The application can perform other work and attempt another read when the stream becomes ready.
However, non-blocking I/O alone does not tell an application when a stream is ready. This is where an I/O polling mechanism becomes useful.
Why PHP 8.6 Introduces a Polling API
Before PHP 8.6, developers commonly used stream_select() to monitor multiple streams.
The function checks whether streams are ready for reading, writing, or have exceptional conditions.
Consider the following example:
<?php
$read = [$client1, $client2, $client3];
$write = null;
$except = null;
$result = stream_select(
$read,
$write,
$except,
5
);
if ($result !== false) {
foreach ($read as $stream) {
$data = fread($stream, 8192);
if ($data !== false && $data !== '') {
echo $data;
}
}
}
This approach works, but developers must rebuild and pass the stream arrays on every polling operation.
There are also platform-dependent limitations. In particular, select-based implementations can encounter descriptor limits, such as the commonly encountered 1024 descriptor limit on some systems.
PHP 8.6 introduces a dedicated polling API that keeps registered handles inside a polling context.
Instead of repeatedly passing stream arrays, developers register streams once and wait for readiness events.
The main benefits include:
Persistent stream registration.
A consistent object-oriented API.
Automatic selection of supported operating system polling backends.
Better suitability for applications managing many connections.
A foundation for asynchronous libraries and event loop implementations.
It is important to understand that the Polling API does not automatically make an entire PHP application asynchronous. Developers must still manage connection states, non-blocking reads, writes, timeouts, and application-level operations.
Understanding the PHP 8.6 Polling API
The new API is available through the Io\Poll namespace.
It provides several important classes and enums.
Component | Purpose |
|---|
Io\Poll\Context | Maintains registered handles and waits for events |
Io\Poll\Handle | Interface representing a pollable handle |
StreamPollHandle | Wraps a PHP stream for polling |
Io\Poll\Watcher | Represents a registered handle and its events |
Io\Poll\Event | Defines readable, writable, and other polling events |
Io\Poll\Backend | Identifies the operating system polling mechanism |
The main component is Context. It manages the streams being monitored and returns the watchers that become ready.
Io\Poll\Context
Context is the starting point for using the Polling API.
It provides methods to register streams, identify the active backend, and wait for events.
Its main methods include:
__construct(): Creates a polling context.
add(): Registers a handle for specific events.
getBackend(): Returns the polling backend selected by the context.
wait(): Waits until registered handles trigger events or a timeout occurs.
The constructor automatically selects a suitable backend when no specific backend is provided.
StreamPollHandle
StreamPollHandle allows PHP streams to participate in the polling system.
For example, a TCP socket can be wrapped as follows:
<?php
$handle = new StreamPollHandle($client);
The class provides two useful methods:
Not every PHP stream can be monitored. The stream must be backed by an operating system file descriptor, and the selected backend must support its type.
Io\Poll\Event
The Event enum defines the conditions that a polling context can monitor.
Event | Description |
|---|
Event::Read | Data is available for reading |
Event::Write | The stream is ready for writing |
Event::Error | An error occurred |
Event::HangUp | The connection or stream was disconnected |
Event::ReadHangUp | The other end closed its writing side |
Event::OneShot | Reports the event once until re-enabled |
Event::EdgeTriggered | Reports changes in readiness state |
Read and Write are the most commonly used events when building basic network services.
The other events become useful when developing more advanced event loops and connection management systems.
Creating Your First Polling Context
Let's start with a simple example using a local stream socket pair.
A socket pair provides two connected streams that can communicate with each other. It is useful for learning how polling works without setting up a separate network server.
<?php
use Io\Poll\Context;
use Io\Poll\Event;
use Time\Duration;
[$reader, $writer] = stream_socket_pair(
STREAM_PF_UNIX,
STREAM_SOCK_STREAM,
STREAM_IPPROTO_IP
);
stream_set_blocking($reader, false);
$context = new Context();
$context->add(
new StreamPollHandle($reader),
[Event::Read],
'reader'
);
// No data is available yet.
$events = $context->wait(
Duration::fromMilliseconds(100)
);
echo "Events received: " . count($events) . PHP_EOL;
// Send data through the other stream.
fwrite($writer, "Hello from PHP 8.6");
$events = $context->wait(
Duration::fromSeconds(1)
);
foreach ($events as $watcher) {
$stream = $watcher->getHandle()->getStream();
$data = fread($stream, 1024);
echo $watcher->getData() . ": " . $data . PHP_EOL;
}
fclose($reader);
fclose($writer);
The first polling operation waits for data but does not receive any because the writer has not sent anything yet.
After writing a message to the second stream, the next polling operation detects that the reader is ready.
The application can then read the message.
This example demonstrates three important operations:
Create a polling context.
Register a stream using StreamPollHandle.
Wait for the stream to become ready and process the returned watcher.
The timeout uses Time\Duration, another feature available in PHP 8.6. It allows developers to express timeouts using readable duration values instead of manually calculating microseconds.
Building a TCP Server With the PHP 8.6 Polling API
Now let's implement a practical TCP server.
The server will accept client connections, monitor them for incoming messages, and return received data to the connected clients.
This example demonstrates how the Polling API can manage multiple connections within a single event loop.
Step 1: Create the TCP Server
First, create a TCP listening socket.
<?php
$server = stream_socket_server(
'tcp://127.0.0.1:8080',
$errno,
$errstr
);
if ($server === false) {
throw new RuntimeException(
"Server creation failed: $errstr ($errno)"
);
}
stream_set_blocking($server, false);
echo "Server started on port 8080" . PHP_EOL;
The stream_socket_server() function creates a listening socket.
The stream_set_blocking() function switches the server socket to non-blocking mode so accepting new connections does not wait indefinitely.
Step 2: Create the Polling Context
Next, initialize the polling context and register the server socket.
<?php
use Io\Poll\Context;
use Io\Poll\Event;
$poll = new Context();
$serverHandle = new StreamPollHandle($server);
$poll->add(
$serverHandle,
[Event::Read],
'server'
);
The server listens for Read events because a listening socket becomes readable when a client connection is ready to be accepted.
The third argument is application-defined data associated with the watcher. Here, it identifies the server connection.
Step 3: Accept Client Connections
When the polling context reports that the server socket is readable, the application can accept an incoming connection.
<?php
$client = stream_socket_accept($server, 0);
if ($client !== false) {
stream_set_blocking($client, false);
$poll->add(
new StreamPollHandle($client),
[Event::Read],
'client'
);
echo "New client connected" . PHP_EOL;
}
The timeout value of zero ensures that the accept operation does not wait for another connection.
After accepting the client, the application switches the connection to non-blocking mode and registers it with the polling context.
Step 4: Read Incoming Client Data
Once a client is registered, the polling context can report when incoming data becomes available.
<?php
foreach ($poll->wait() as $watcher) {
$stream = $watcher->getHandle()->getStream();
$data = fread($stream, 8192);
if ($data === false || $data === '') {
$watcher->remove();
fclose($stream);
continue;
}
echo "Received: " . $data . PHP_EOL;
fwrite($stream, "Server received: " . $data);
}
The watcher provides access to the registered handle.
The application reads the incoming data and sends a response to the client.
If the connection is closed or reaches the end of the stream, the watcher is removed and the stream is closed.
For a real production server, this basic read-and-write approach needs additional handling for partial writes, buffered responses, error events, and connection lifecycle management.
Complete TCP Server Example
The following example combines the previous steps into one working structure.
<?php
use Io\Poll\Context;
use Io\Poll\Event;
$server = stream_socket_server(
'tcp://127.0.0.1:8080',
$errno,
$errstr
);
if ($server === false) {
throw new RuntimeException(
"Unable to start server: $errstr ($errno)"
);
}
stream_set_blocking($server, false);
$poll = new Context();
$poll->add(
new StreamPollHandle($server),
[Event::Read],
'server'
);
echo "TCP server running on 127.0.0.1:8080" . PHP_EOL;
while (true) {
foreach ($poll->wait() as $watcher) {
$stream = $watcher->getHandle()->getStream();
if ($stream === $server) {
$client = stream_socket_accept($server, 0);
if ($client !== false) {
stream_set_blocking($client, false);
$poll->add(
new StreamPollHandle($client),
[Event::Read],
'client'
);
echo "Client connected" . PHP_EOL;
}
continue;
}
$data = fread($stream, 8192);
if ($data === false || $data === '') {
$watcher->remove();
fclose($stream);
echo "Client disconnected" . PHP_EOL;
continue;
}
echo "Received: " . $data . PHP_EOL;
fwrite(
$stream,
"Server received: " . $data
);
}
}
Save the file as server.php and run it using PHP 8.6:
php server.php
You can connect to the server from another terminal using a TCP client such as netcat:
nc 127.0.0.1 8080
Enter a message and the server should return a response.
This example demonstrates the basic polling workflow. It is intended for learning and local testing, not direct deployment as a production server.
Understanding Polling Backends
One of the important advantages of the PHP 8.6 Polling API is its ability to use different operating system mechanisms.
The Context constructor accepts an optional Backend enum value.
When the application uses the default Auto backend, PHP selects a suitable available implementation.
Backend | Operating System Support | Description |
|---|
Epoll | Linux | Efficient event notification for large numbers of file descriptors |
Kqueue | BSD-based systems and macOS | Kernel event notification mechanism |
Event Ports | Solaris and supported systems | Operating system event notification |
WSAPoll | Windows | Windows socket polling mechanism |
Poll | Supported systems | General polling mechanism |
Developers can inspect the backend selected by PHP:
<?php
use Io\Poll\Context;
$poll = new Context();
$backend = $poll->getBackend();
echo "Selected backend: " . $backend->name . PHP_EOL;
This can be useful when troubleshooting differences between development, testing, and production environments.
The available backend depends on the operating system and PHP build.
Understanding Level-Triggered and Edge-Triggered Events
The Polling API also provides two event-reporting approaches: level-triggered and edge-triggered polling.
Understanding the difference is important when developing high-performance event loops.
Level-Triggered Polling
In level-triggered polling, an event continues to be reported while the monitored condition remains true.
For example, if data is available to read but the application reads only part of it, the stream can continue to be reported as readable.
This behavior is easier to manage because the application can process available data in smaller portions.
It is generally a good starting point for developers building their first event-driven applications.
Edge-Triggered Polling
Edge-triggered polling reports changes in the readiness state rather than repeatedly reporting a condition that remains true.
For example, when new data arrives, the application receives a readiness notification.
If the application does not read all available data, it should not assume that another event will immediately be generated for the remaining data.
This means the application generally needs to read until the stream would block before returning to the polling loop.
PHP provides the Event::EdgeTriggered modifier for this purpose.
However, edge-triggered polling is not supported by every backend. PHP provides a method to check backend support:
<?php
use Io\Poll\Context;
use Io\Poll\Event;
$poll = new Context();
$events = [Event::Read];
if ($poll->getBackend()->supportsEdgeTriggering()) {
$events[] = Event::EdgeTriggered;
}
echo "Using events: " . count($events) . PHP_EOL;
Only Epoll and Kqueue support edge-triggered events in the documented PHP 8.6 implementation.
For most beginner applications, level-triggered polling is easier to implement and maintain.
Handling Read and Write Events
Reading and writing are two different operations in non-blocking network applications.
A stream may be ready for reading but not ready for writing. Similarly, a write operation may accept only part of the supplied data.
This is why production applications should monitor both Read and Write events when necessary.
Consider an application that needs to send a large response to a client.
Instead of assuming that one fwrite() operation sends everything, maintain an output buffer.
<?php
$outputBuffer = "Large response data";
$written = fwrite($client, $outputBuffer);
if ($written === false) {
throw new RuntimeException(
"Unable to write to client."
);
}
$outputBuffer = substr(
$outputBuffer,
$written
);
If the buffer still contains data, the application should continue monitoring the stream for write readiness and attempt to send the remaining bytes.
The watcher can be modified to monitor additional events using its event-modification methods.
This approach prevents the application from losing data when a non-blocking write completes only partially.
Handling Timeouts With the Polling API
Timeout management is important for network applications.
A client may connect to a server but never send a complete request. Without timeouts, applications can waste resources maintaining inactive connections.
PHP 8.6 allows developers to specify a timeout when calling Context::wait().
For example:
<?php
use Io\Poll\Context;
use Time\Duration;
$poll = new Context();
$events = $poll->wait(
Duration::fromSeconds(5)
);
if (count($events) === 0) {
echo "Polling timeout reached." . PHP_EOL;
}
The polling operation waits for events for up to the specified duration.
If no event is received during that period, it returns an empty array.
The timeout is useful for implementing periodic maintenance tasks, checking inactive connections, and processing application-level timers.
It is important to remember that a polling timeout does not automatically disconnect inactive clients. The application must implement its own timeout tracking and cleanup logic.
PHP 8.6 Polling API vs. stream_select()
Both approaches can monitor multiple streams, but their programming models are different.
Feature | stream_select() | PHP 8.6 Polling API |
|---|
Programming model | Procedural | Object-oriented |
Stream registration | Arrays passed repeatedly | Handles registered in Context |
Event monitoring | Read, write, exceptional conditions | Event enum |
Backend selection | Based on underlying select implementation | Automatic or explicit backend selection |
Timeout handling | Seconds and microseconds | Time\Duration |
Persistent registration | No | Yes |
Event loop integration | Possible | Designed as a foundation for event loops |
Platform limitations | Depends on select implementation | Uses available polling backends |
The new API provides a cleaner way to maintain registered streams and offers access to more suitable operating system polling mechanisms.
However, stream_select() remains useful for existing applications and projects that need to support older PHP versions.
There is no reason to replace every existing stream_select() implementation immediately. Migration should be based on application requirements and runtime compatibility.
Advantages of the PHP 8.6 Polling API
The new Polling API provides several benefits for developers building network applications.
Persistent Stream Registration
Developers register handles once instead of rebuilding arrays for every polling operation.
This makes the event loop easier to organize.
Better Platform Integration
The API can use native operating system polling mechanisms.
This gives PHP applications access to mechanisms designed for monitoring multiple file descriptors.
Cleaner Event Management
The Event enum provides a consistent way to define which conditions an application wants to monitor.
It also supports advanced event modifiers.
Suitable for Event Loop Development
The API provides a foundation for libraries that need to manage asynchronous network operations.
This includes event-driven servers, socket-based applications, and networking frameworks.
Built Into PHP Core
The Polling API is part of PHP core in PHP 8.6 and does not require installing a separate extension.
Disadvantages and Limitations
Although the Polling API is useful, it is not a complete asynchronous networking framework.
Requires PHP 8.6 or Compatible Polyfill
The native API requires PHP 8.6 or later.
Applications running older versions need a different implementation or a compatible polyfill.
Requires Manual Connection Management
Developers are responsible for accepting connections, processing events, handling errors, and removing disconnected clients.
Not Every Stream Is Pollable
StreamPollHandle works with streams backed by operating system file descriptors.
Regular files and certain other stream types may not be supported by a particular backend.
Non-Blocking Writes Need Additional Logic
An application cannot assume that fwrite() always sends the complete response.
It must maintain output buffers and handle partial writes.
Does Not Automatically Make Database Operations Asynchronous
The Polling API monitors supported I/O handles. It does not automatically convert blocking database queries, file operations, or other synchronous application code into non-blocking operations.
Best Practices for Production Applications
When using the PHP 8.6 Polling API in a real application, consider the following practices.
Use non-blocking mode for streams that are managed through the event loop. This prevents read and write operations from waiting indefinitely.
Maintain connection state separately. Store information such as connection status, authentication state, request buffers, and last activity time.
Handle partial writes correctly. Maintain an output buffer and continue writing when the stream becomes ready.
Remove disconnected clients immediately. Call the watcher's remove() method and close the corresponding stream to prevent unnecessary resource usage.
Use appropriate timeouts. Define connection, request, and idle timeouts based on application requirements.
Monitor error and hang-up events. Do not rely only on Read events to identify every connection failure.
Avoid unnecessary Write monitoring. A stream may remain writable most of the time, which can cause repeated event notifications. Monitor Write only when there is pending output.
Keep event handlers short. Long-running operations can delay processing other ready connections in the same event loop.
Validate incoming data. Network input should always be treated as untrusted. Apply request-size limits and protocol validation.
Test across operating systems. The selected polling backend and supported event features may differ between environments.
Monitor resource usage. Track open connections, memory consumption, buffer sizes, and event processing delays.
Use established event-loop libraries when appropriate. The native API provides low-level polling functionality, while higher-level libraries can provide connection management and asynchronous abstractions.
Common Mistakes Developers Should Avoid
Forgetting to Enable Non-Blocking Mode
Registering a stream with the polling context does not automatically make every operation non-blocking.
Use stream_set_blocking() when appropriate.
stream_set_blocking($client, false);
Otherwise, a read operation may block the entire event loop.
Registering the Same Handle Multiple Times
A handle can only be watched once by the same polling context.
Creating another StreamPollHandle around the same stream does not create an independent registration.
Maintain a reference to the existing watcher when managing connections.
Assuming Every Read Event Contains a Complete Request
TCP is a byte-stream protocol. A single read operation does not necessarily contain a complete application-level message.
Applications should maintain input buffers and parse messages according to their protocol.
Ignoring Partial Writes
A non-blocking write may send fewer bytes than requested.
Always check the number of bytes returned by fwrite() and preserve unsent data.
Using Edge-Triggered Events Without Reading All Available Data
With edge-triggered polling, applications must carefully process available data.
Failing to drain the stream can leave unread data without another readiness notification.
Forgetting to Remove Watchers
When a connection closes, remove its watcher and close the stream.
Otherwise, the application may continue maintaining unnecessary connection state.
Troubleshooting PHP 8.6 Polling API Issues
Problem | Possible Cause | Recommended Solution |
|---|
Class Context not found | PHP version does not support the API | Verify PHP 8.6 or compatible polyfill |
InvalidHandleException | Stream is closed or unsupported | Check stream validity and backend compatibility |
HandleAlreadyWatchedException | The same stream is already registered | Reuse the existing watcher |
No events received | Stream is not ready or the wrong event is monitored | Verify the registered events and stream state |
Application becomes unresponsive | A blocking operation is running inside the event loop | Use non-blocking operations and avoid long-running handlers |
Data is incomplete | Read operation returned only part of the request | Maintain an input buffer and parse complete messages |
Response is truncated | fwrite() sent only part of the data | Maintain an output buffer and monitor Write events |
Edge-triggered registration fails | Selected backend does not support edge triggering | Check supportsEdgeTriggering() before enabling it |
A useful troubleshooting approach is to first verify the selected backend, then check stream validity, registered events, and the behavior of read and write operations.
When Should You Use the PHP 8.6 Polling API?
The Polling API is particularly useful when an application needs to monitor multiple network connections within one execution loop.
Consider using it for:
TCP servers that manage multiple clients.
Real-time messaging systems.
Socket-based communication services.
Custom event loop implementations.
Network monitoring applications.
Applications that need to monitor several supported streams.
It may not be necessary for traditional request-response PHP applications that run under PHP-FPM and handle each HTTP request independently.
For those applications, established frameworks and runtime models may already provide the required request handling and concurrency.
Conclusion
PHP 8.6 introduces a new Polling API that makes non-blocking I/O and stream monitoring more structured. Through Io\Poll\Context, StreamPollHandle, and the Event enum, developers can register streams and wait for readiness notifications without repeatedly rebuilding stream arrays.
The API also provides access to operating system polling mechanisms such as epoll and kqueue, making it a useful foundation for event-driven networking applications.
However, polling is only one part of building a reliable asynchronous system. Developers still need to manage connection states, handle partial reads and writes, implement timeouts, and clean up disconnected clients.
For developers building TCP services, custom event loops, or real-time communication systems, understanding the PHP 8.6 Polling API is a valuable step toward writing more efficient network-oriented PHP applications.
Join the conversation! Your thoughts help the community grow.