Websockets in PHP without a process of your own

PHP can serve websockets, but not from the requests that answer your pages: PHP-FPM gives each request a worker until its answer is sent, and a websocket is a connection that stays open for hours. So a websocket in PHP runs in a script of its own, started from the command line and kept running, with an event loop that watches every connection at once, and your site has to hand that script each event to send.
This post shows such a server with Ratchet, why it cannot live inside your site, what running it for real users takes, and how to send live events from plain PHP with no websocket process at all.
Why a PHP request cannot hold a websocket
A websocket is a two-way connection between a browser and a server that stays open, so either side can send at any moment. It starts as an HTTP request that asks to be upgraded, and from then on it is no longer a request with an answer but a line that stays open for as long as the page does.
PHP was built the other way. Under PHP-FPM, the web server hands each request to one worker of a pool. The worker runs your script, sends the answer and takes the next request. The pool has a fixed size, and the PHP manual says pm.max_children sets the limit on how many requests are served at once. A websocket held in a request would keep its worker busy for as long as its page stays open. With 20 workers, 20 open pages would take all of them, and the site would stop answering everyone else.
The servers in front of PHP see it the same way. nginx closes the connection to PHP-FPM when PHP sends nothing for 60 seconds, by default, and hosts set limits of their own on how long a request may run.
Long polling and server-sent events look like a way around it, and in PHP they meet the same wall: each waiting request holds a worker. WordPress runs into exactly this, as our post on WordPress and websockets explains, and so does every PHP app, with a framework or without one.
A websocket server in PHP
The answer in PHP is a second program: a script you start with php from the command line, which never ends. It listens on a port and runs an event loop, which waits on every open connection at once and wakes up for the one that has something to say. A library does the handshake and the framing of the WebSocket protocol for you. The best known is Ratchet, built on the event loop of ReactPHP:
composer require cboden/ratchet<?php
// chat.php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
class Chat implements MessageComponentInterface {
private SplObjectStorage $clients;
public function __construct() {
$this->clients = new SplObjectStorage();
}
public function onOpen( ConnectionInterface $conn ) {
$this->clients->attach( $conn );
}
// Pass each message to everyone else connected.
public function onMessage( ConnectionInterface $from, $msg ) {
foreach ( $this->clients as $client ) {
if ( $client !== $from ) {
$client->send( $msg );
}
}
}
public function onClose( ConnectionInterface $conn ) {
$this->clients->detach( $conn );
}
public function onError( ConnectionInterface $conn, \Exception $e ) {
$conn->close();
}
}
// ws://localhost:8080/chat, for pages served from localhost.
$app = new Ratchet\App( 'localhost', 8080 );
$app->route( '/chat', new Chat(), [ 'localhost' ] );
$app->run();Start it with php chat.php, and a page connects with the WebSocket API every browser has:
const socket = new WebSocket( 'ws://localhost:8080/chat' );
socket.onopen = () => socket.send( 'hello' );
socket.onmessage = ( event ) => console.log( event.data );Open that page in two tabs, served from localhost, and each one prints what the other sends. The third argument of route() lists the hosts whose pages may connect, because a page on any other site can open a websocket to your server, and the standard leaves refusing it to you. [ '*' ] lets every site in.
On PHP 8.5 this runs as it is, after a screen of deprecation notices: the last release of Ratchet, 0.4.4, came out in December 2021, and its README says the project is being revived. AMPHP has a websocket server of its own for PHP 8.1 and later, and the Swoole extension adds a server to PHP itself. Each of them is a process you keep running, and that is the part that matters below.
Once the server runs on a public address, our WebSocket test connects to it from a browser and explains any close code. If a browser only reports that the connection failed, our post on WebSocket error 1006 shows how to find the cause.
What a long-running PHP process changes
Two things in that server decide everything after it. $clients lives in the memory of this one process, and the process keeps running for weeks. Most PHP code is written for neither.
- One slow call stops everyone. The event loop runs your code one piece at a time. While
onMessage()waits for a PDO query, afile_get_contents()of a URL or asleep(), no other connection is served. ReactPHP, which Ratchet runs on, is non-blocking by default and sends blocking work to workers. So the database calls your site makes everywhere need clients built for the loop here, or a queue. - Memory is never handed back. Under PHP-FPM, everything a request built is gone when it ends, so a static cache or an array that only grows does no harm. In a process that runs for weeks, it grows until something restarts it.
- New code needs a restart. The script loaded your files once, when it started, so a deploy changes nothing in it until it starts again.
- Your site and the server are two programs. The request that saved an order runs in PHP-FPM, and the browsers are connected to the websocket script, whose memory that request cannot reach. Ratchet's own guide to sending updates from an existing site passes each one over ZeroMQ, which takes the libzmq library and a PECL extension. A Redis channel, or a small HTTP route in the websocket script, does the same job.
- Knowing who is connecting. A browser sends your session cookie with the upgrade when the websocket is on your own domain, but the script has to read that session itself, and PHP keeps sessions in files on one server by default. The
WebSocketof a browser cannot set a header, so the other way is a short-lived token in the address, signed by your site and checked before the connection opens.
What running it for real users takes
The rest of the list comes with the first real users:
- Shell access and a process manager. The script has to be started and kept alive, which the Ratchet README states as a requirement. Shared hosting rarely allows it. On a server of your own, systemd or Supervisor starts it again when it crashes.
- A port, a certificate and a proxy. Browsers connect over
wss://on your domain, usually through nginx or Apache in front. The nginx docs explain that a proxy passes theUpgradeandConnectionheaders on only when told to, and that it closes a proxied connection with no data for 60 seconds by default. - A heartbeat. So the server pings every connection on a timer. That keeps proxies from closing a quiet one, and it finds the connections that died without a word, which otherwise stay in
$clients. - More than one process. One event loop uses one core of the CPU. Two processes, or two servers, each know only their own connections, so every event has to cross a channel they share, usually Redis. Redis pub/sub delivers at most once, so a process that was reconnecting at that moment never gets the event.
- Deploys. A restart drops every connection. The
WebSocketof a browser does not reconnect by itself, so your page code does, after a delay that grows and differs for each browser. What was sent while a page was away is gone, unless you keep recent events and replay them from the last one it saw.
None of this is unusual, and plenty of teams run it well. It is a second system beside your PHP app all the same, written in a style the rest of your code never needs.
Or keep no websocket process at all
A hosted realtime service takes the connections off your servers. The browsers connect to the service. Your PHP code sends each event in one short HTTPS request, from the very request that saved the change, and the service delivers it to every page that should get it. Nothing in your app runs longer than a request, so PHP-FPM stays as it is.
| Setup | Where connections live | What you run |
|---|---|---|
| PHP-FPM alone | Nowhere, each request ends | Polling, a worker for each wait |
| A websocket script | In its memory | A process, a proxy and a channel from your site |
| A hosted service | On its servers | One request for each event |
PHP on WordPlus Cloud
With WordPlus Cloud, one Composer package is your server side, and it carries the browser files too, so there is no Node to install:
composer require wordplus/realtime-php # PHP 8.1 or later, with sodiumYour app declares its rooms once, each with a rule for who may join. This is the room of an order, for its customer:
// src/realtime.php, required by every request that needs it
use WordPlus\Realtime\Realtime;
$realtime = Realtime::fromEnvironment(); // WORDPLUS_SITE, WORDPLUS_SECRET, WORDPLUS_LOCAL_KEY
// The room of an order, order:1042: its customer may join, and the last 20 updates are kept.
$realtime->room( 'order:{id}', function ( $user, array $p ) {
if ( null === $user ) {
return false;
}
return order_owner( $p['id'] ) === $user;
}, [ 'history' => 20 ] );Two short routes serve the browser files and answer the pages that ask to join, for the user of the session:
// public/index.php, or your router
if ( $realtime->respondFile() ) {
exit;
}
if ( preg_match( '#^/api/realtime/(auth|calls|keys|webhook)$#', parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), $route ) ) {
session_start( [ 'read_and_close' => true ] );
$realtime->respond( $route[1], $_SESSION['user_id'] ?? null );
exit;
}After your own work is saved, tell everyone in the room:
set_status( $id, 'shipped' );
$realtime->to( "order:$id" )->emit( 'updated', [ 'status' => 'shipped' ] );The page gets its settings from <?= $realtime->head( $userId ) ?> in its <head>, with an import map for the client, so this file runs as it is, with no bundler:
import { connect } from '@wordplus/realtime';
const rt = await connect( window.wordplusRealtimeConfig );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );That emit is one HTTPS request, so it runs the same in a PHP-FPM request, a cron job or a queue worker. Beyond it:
- Nothing to keep running. No websocket script, no proxy rules and no channel between your site and a server. Any of your servers answers any request and sends to any room.
- Nothing lost on a reconnect. A room keeps its last events, so a page that comes back gets what it missed, in order.
- Every page of one user.
$realtime->toUser( 42 )->emit( 'notice', [ 'text' => 'Your order shipped' ] )reaches every tab and device they have open. A user with nothing open gets nothing, so send an email for what must reach them. - One connection for every tab. The tabs of a browser share one connection, so a person with three tabs open counts once.
- Sealed on the way. What your server sends to a room with a rule travels encrypted with keys only your server and your users hold.
- What pages send comes to you. A webhook brings it to your PHP, signed and checked by the package before your handler sees it, and tried again for 24 hours if your server does not answer.
- More than events. Who is online, calls that ring in every tab, group calls and live streams come on the same connection, with a ready-made chat, call screen and player, or your own interface on the same API.
In Symfony, Slim or a router of your own, answerRequest() gives the status and body to answer with in place of respond(). Laravel has its broadcasting, and our post on websockets in Laravel shows the same cloud behind Echo.
When your own server fits better
A hosted service is not right for every job. Your PHP code hears what pages send through a webhook, an HTTP request that can arrive more than once, and not in a loop beside each connection. A game or a control system where the server has to answer each message within milliseconds belongs on a server of its own. So does a protocol of your own that other programs speak over a plain websocket. And a tool for a few dozen people, on a server you already run, may never need more than the Ratchet script at the top of this post.
Start with the guide
The PHP guide has the whole setup, and the PHP demo is a small shop in plain PHP built on it, where an order turns to shipped in another window as you click. The same question has other answers in Node.js, where one process holds connections well, and in Django and Flask.
WordPlus Cloud for Apps is priced by concurrent connections, starting from 1,000, billed monthly or yearly, and our post on realtime pricing explains how counting by the connection works. See what it does for apps, our WebSocket API page shows rooms, presence and events in each stack, and the apps pricing has the numbers. Questions about your integration? Write to us.