WebSocket in PHP: Building Real-Time Applications from Scratch

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

WebSocket on PHP: creating real-time applications from scratch



Modern web applications require instant response to user actions. The standard HTTP protocol, operating on a "request-response" principle, is poorly suited for tasks where data needs to be updated in real time — chats, notifications, stock quotes, or online games. The solution to this problem is WebSocket. In this article, we will analyze how to implement WebSocket on PHP, create a simple chat, and review best practices.



What is WebSocket and why is it needed in PHP?



WebSocket is a communication protocol that provides a persistent two-way connection between a client (browser) and a server. Unlike HTTP, after establishing a connection, data can be transmitted in both directions at any time without repeated requests. This is critically important for real-time applications.



PHP is traditionally considered a language for server-side logic operating on a "start-execute-terminate" scheme. However, with the emergence of asynchronous libraries such as Ratchet and ReactPHP, PHP has become a full-fledged tool for creating WebSocket servers. The main advantages of using WebSocket on PHP:



  • Instant data delivery — without delays from repeated HTTP requests.
  • Reduced server load — one connection replaces dozens of Long Polling requests.
  • Ease of integration — if your project is already on PHP, you don't need to change the technology stack.


Installing and configuring the Ratchet library



To work with WebSocket in PHP, we will use the Ratchet library (in conjunction with ReactPHP). Installation is done via Composer:



composer require cboden/ratchet


After installation, we will create a basic WebSocket server class. In Ratchet, the server is implemented through the MessageComponentInterface interface, which contains four methods:



  • onOpen — called when a new client connects.
  • onMessage — processes an incoming message.
  • onClose — triggered when a client disconnects.
  • onError — handles connection errors.


Example of a simple server:



<?phpuse Ratchet\\MessageComponentInterface;use Ratchet\\ConnectionInterface;

class ChatServer implements MessageComponentInterface { protected $clients;

public function __construct() { $this->clients = new \\SplObjectStorage; }

public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "New connection: {$conn->resourceId}"; }

public function onMessage(ConnectionInterface $from, $msg) { foreach ($this->clients as $client) { if ($from !== $client) { $client->send($msg); } } }

public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "Connection {$conn->resourceId} closed"; }

public function onError(ConnectionInterface $conn, \\Exception $e) { echo "Error: {$e->getMessage()}"; $conn->close(); }}


Starting the WebSocket server and client side



To start the server, create a server.php script:



<?phprequire __DIR__ . '/vendor/autoload.php';

use Ratchet\\Server\\IoServer;use Ratchet\\Http\\HttpServer;use Ratchet\\WebSocket\\WsServer;

$server = IoServer::factory( new HttpServer( new WsServer( new ChatServer() ) ), 8080);

echo "WebSocket server started on port 8080";$server->run();


Start the server with the command:



php server.php

Blogs

Book Recommendations