Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 147 ยท Advanced PHP

Sockets and Network Streams

Learn PHP network programming with streams - stream_socket_server, stream_socket_client, accept, stream_socket_pair, timeouts, non-blocking mode and stream_select.

Most PHP code talks to the network indirectly: through a database driver, an HTTP client or a framework. Underneath, all of them use sockets: endpoints that send and receive bytes between programs. PHP exposes sockets through the same stream API you use for files, so once you know fread() and fwrite() you already know most of what you need.

This lesson uses the stream functions stream_socket_server(), stream_socket_client(), stream_socket_accept(), stream_socket_pair() and stream_select(). They ship with every PHP build, unlike the lower-level sockets extension. You will build a tiny echo protocol, learn why reads can block, and see how stream_select() lets one process watch many connections. If streams are new to you, read Streams and Wrappers first.

The big picture

A TCP conversation has two roles. The server binds to an address and port, listens, and accepts connections. The client connects to that address. After the connection is accepted, both sides hold a stream and can read and write.

sequenceDiagram
    participant S as Server
    participant C as Client
    S->>S: stream_socket_server("tcp://127.0.0.1:0")
    C->>S: stream_socket_client(address)
    S->>S: stream_socket_accept()
    C->>S: fwrite("hello\n")
    S->>C: fwrite("echo: hello\n")
    C->>S: fclose()

The server listens first; the client connects; the accepted connection is a plain stream for both sides.

Port 0 means "let the operating system pick a free port". After binding you ask for the actual address with stream_socket_get_name($server, false). In our examples everything runs inside one process on the loopback address 127.0.0.1, so nothing leaves your machine.

Your first server and client

Because the operating system queues incoming connections, a single script can open a listening socket, connect to it, and then accept. No threads needed.

PHP An echo exchange over TCP loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice what happens after the server closes its end: fgets() on the client returns false and feof() becomes true. That is how you detect that the other side hung up.

The address string has the form tcp://host:port. Other transports use the same functions:

Address Meaning
tcp://127.0.0.1:8080 TCP on IPv4 loopback
tcp://[::1]:8080 TCP on IPv6 loopback
udp://127.0.0.1:9999 UDP datagrams
unix:///tmp/app.sock Unix domain socket (local only, no port)
tls://example.com:443 TLS-encrypted TCP (client side)
ssl://... Older alias for TLS

Binding to 0.0.0.0 accepts connections from any network interface, which is rarely what you want for a development server. Use 127.0.0.1 unless you mean to expose the service.

Messages need framing

TCP is a byte stream, not a message stream. If you write "abc" and then "def", the other side may read "abcdef" in one go, or "ab" then "cdef". You must tell the receiver where a message ends. Common approaches:

  • Delimiters. One message per line (\n), which is what fgets() expects.
  • Length prefix. Send the byte count first, then the payload. Binary-safe and fast.
  • Fixed size. Every message is the same number of bytes.

Here is a length-prefixed protocol using stream_socket_pair(), which returns two already-connected streams. It is perfect for testing and for talking between a parent and a child process without any port at all:

PHP Length-prefixed messages over a socket pair

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

pack('N', ...) writes an unsigned 32-bit integer in network byte order. The readExactly() helper loops because fread() on a socket may return fewer bytes than you asked for. Never assume a single read gives you a whole message.

Blocking, timeouts and non-blocking mode

By default a socket read blocks: fgets() waits until data arrives or the other side closes. A server that blocks on one slow client is stuck. You have three tools:

  1. Timeouts. stream_set_timeout($stream, 2) makes reads give up after two seconds. Check stream_get_meta_data($stream)['timed_out'] afterwards.
  2. Non-blocking mode. stream_set_blocking($stream, false) makes reads return immediately with whatever is available (possibly nothing).
  3. Multiplexing with stream_select(), shown next.
PHP Timeout and non-blocking reads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first var_dump prints string(0) "": no data, no waiting. After the write, the line arrives. In the third step nothing more is sent, so the read waits 0.2 seconds, returns false and reports timed_out as true. A timed-out stream is still usable.

Watching many streams with stream_select

Real servers handle many clients at once. stream_select($read, $write, $except, $seconds) takes arrays of streams and returns only those that are ready. When it returns, the arrays contain just the ready streams, so always rebuild them before the next call. A read-ready stream will not block when you read from it; for a listening server socket, "ready" means a new connection is waiting to be accepted.

flowchart TD
    A["Build $read = server + all clients"] --> B["stream_select($read, ..., timeout)"]
    B --> C{"Server in $read?"}
    C -- yes --> D["accept new client, add to list"]
    C -- no --> E
    D --> E["For each client in $read"]
    E --> F{"fread returns data?"}
    F -- yes --> G["handle request, reply"]
    F -- "no (closed)" --> H["fclose and remove from list"]
    G --> A
    H --> A

One loop, many connections: select tells you which streams can be read without waiting.

The next example runs a miniature single-process server loop with three clients. To stay deterministic the clients write first, and the server loop runs until all have been served.

PHP A select loop serving three clients

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The server never blocks on one client: each pass asks the operating system which sockets have something to say. The order the server handles clients may vary, which is why the program prints results per client and sorts the list before showing it.

For thousands of connections stream_select() (which uses select(2), limited to 1024 descriptors on many systems) is replaced by event loops built on epoll/kqueue, such as the ones in ReactPHP, Amp, Swoole or PHP's Fibers-based libraries. The ideas, read-ready streams and non-blocking I/O, stay the same.

HTTP by hand

HTTP is just text over TCP, so you can speak it on a socket. This example runs a toy HTTP responder on loopback and fetches a path from it with a hand-written request:

PHP A hand-written HTTP exchange

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This is only for learning. Real HTTP has chunked encoding, keep-alive, TLS, redirects and many edge cases; use curl or a client library for actual requests (see HTTP Headers and Redirects), and PHP-FPM or a framework server for incoming ones.

Safety and good habits

Sockets accept input from strangers. Never trust lengths, never read unbounded data into memory, and never unserialize() or eval() what arrives. Set a maximum message size and drop clients that exceed it.

  • Always check the return value of stream_socket_client() and stream_socket_server(); they return false on failure and fill $errno and $error.
  • Set timeouts so one stalled peer cannot hang your script. default_socket_timeout in php.ini sets the default.
  • Close streams you open. Leaking sockets exhausts file descriptors.
  • Bind to loopback for local tools; use TLS (tls://, stream_context_create with ssl options) for anything crossing a network, and keep certificate verification on. See Security Basics.
  • Remember the web server model: classic PHP-FPM requests are short-lived. Long-running socket servers belong in CLI scripts run by a process manager.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does binding with tcp://127.0.0.1:0 do?

    Port 0 asks the OS for any free port, and 127.0.0.1 limits access to the local machine. Read the real port with stream_socket_get_name().
  2. 2. Why do protocols need message framing on TCP?

    Message boundaries are not preserved. Use delimiters or length prefixes so the receiver knows where each message ends.
  3. 3. After stream_select($read, $write, $except, 1) returns, what does $read contain?

    stream_select modifies the arrays in place, leaving only ready streams. Rebuild the array before every call.
  4. 4. A listening server socket appears in $read after stream_select. What does that mean?

    For a listening socket, 'readable' means an incoming connection is pending. Accept it and add the new stream to your list.
  5. 5. What does fgets() return on a client stream after the peer closed its end and all data was consumed?

    End of stream is signalled with false from the read function and true from feof().

Summary

  • PHP sockets are streams: stream_socket_server() listens, stream_socket_accept() takes a connection, stream_socket_client() connects.
  • Use tcp://127.0.0.1:0 for local experiments and read the chosen port with stream_socket_get_name().
  • TCP delivers bytes, not messages: frame them with newlines or length prefixes and loop until you have the full message.
  • Control waiting with stream_set_timeout(), stream_set_blocking() and stream_select().
  • stream_socket_pair() gives two connected streams without any port.
  • Validate sizes, set timeouts, close streams and use TLS across networks.

Next up: What's New in PHP.