WebSocket in PHP: Real-Time Applications from A to Z

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

What is WebSocket and why it is needed in PHP



The traditional HTTP protocol works on a "request-response" scheme: the client sends a request, the server processes it and returns a response. To receive new data, the client has to constantly reload the page or use AJAX-polling (periodic requests to the server). This approach creates excessive load and does not provide true "live" communication.



WebSocket (RFC 6455) is a protocol that establishes a permanent bidirectional connection between the client (browser) and the server. After the handshake, data can be transmitted in both directions in real time without repeated HTTP requests. This is an ideal solution for:



  • Chats and messengers
  • News feeds and notifications
  • Collaborative document editing
  • Games and auctions
  • Monitoring and dashboards


Many believe that PHP is not suitable for real-time tasks due to its synchronous nature. However, with the advent of libraries like Ratchet and ReactPHP, the situation has changed dramatically. PHP can efficiently work with WebSocket using an event-driven architecture and non-blocking I/O.



Architecture of a WebSocket application in PHP



Before writing code, it is important to understand how a WebSocket connection works on the PHP server side.



Connection establishment stages



  1. HTTP handshake: The client sends a special HTTP request with the header Upgrade: websocket. The server checks the Sec-WebSocket-Key and returns a response with status 101 Switching Protocols.
  2. Protocol switching: After a successful handshake, the connection is switched to WebSocket mode. Further data exchange occurs via binary frames.
  3. Duplex communication: The server and client can send messages at any time until the connection is closed by one of the parties.


Synchronous PHP vs Asynchronous PHP



A regular PHP script works synchronously: one request — one process, after the response the script terminates. WebSocket requires a continuously running process that listens on a port and handles many simultaneous connections. This is where ReactPHP comes to the rescue — a library that implements an event loop for PHP.



The Ratchet library is built on top of ReactPHP and provides a convenient interface for creating WebSocket servers. It handles low-level socket work, frame parsing, and connection management.



Practical implementation: creating a real-time chat



Let's look at creating a simple WebSocket chat using Ratchet. This example can be adapted for any real-time tasks.



Step 1: Installing dependencies



Make sure you have Composer (a dependency manager for PHP) installed. Install Ratchet and its dependencies:



composer require cboden/ratchet


Step 2: Creating the handler class



Let's create a file ChatServer.php that will manage connections and messages:



<?phpnamespace MyApp;

use Ratchet\\MessageComponentInterface;use Ratchet\\ConnectionInterface;

class ChatServer implements MessageComponentInterface{ protected $clients;

public function __construct() { // SplObjectStorage — a convenient way to store connection objects $this->clients = new \\SplObjectStorage; echo "Server started!"; }

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

public function onMessage(Connectio

Blogs

Book Recommendations