WebSockets in PHP: Creating Real-Time Applications Without Magic
\n\nHave you ever wondered why notifications in modern web applications arrive instantly, and chats work without constantly pressing F5? The secret is WebSockets. And yes, PHP can do real-time too. In this article, we'll figure out how to make PHP work with WebSockets, write a live chat and notifications, and most importantly — do it without pain and unnecessary libraries.
\n\nIf you're used to PHP being "request-response," get ready to be surprised. With WebSockets in PHP, you can create full-fledged real-time applications: from a simple chat to a multiplayer game. And all of this — in your favorite language.
\n\nWhat are WebSockets and Why Does PHP Need Them?
\n\nWebSocket is a protocol for two-way communication between a client and a server. Unlike regular HTTP, where the client constantly pings the server asking "so, any news?", WebSocket keeps the connection open. The server itself sends data to the client when it becomes available.
\n\nFor PHP, this is a real breakthrough. Previously, real-time was the domain of Node.js or Python with asyncio. But now real-time applications in PHP are a reality. Thanks to libraries like Ratchet and Swoole, PHP can work as a long-running process, handling thousands of simultaneous connections.
\n\nWhere can this be useful?
\n- \n
- Chats and messengers; \n
- Notification systems (new orders, messages); \n
- Collaborative document editing; \n
- Online games and quizzes; \n
- Real-time monitoring and dashboards. \n
Preparation: What You Need to Get Started
\n\nTo work with a WebSocket server in PHP, we'll need:
\n- \n
- PHP 7.4 or higher (preferably 8.x); \n
- Composer — a package manager; \n
- The Ratchet library (or Swoole for production); \n
- A basic understanding of OOP and working with the console. \n
Let's install Ratchet via Composer:
\ncomposer require cboden/ratchet\n\nAfter installation, you'll have a vendor folder and a composer.json file. Everything is ready to write your first real-time application in PHP.
\n\nWriting a Simple WebSocket Server in PHP
\n\nLet's create a file server.php. This will be our WebSocket server PHP, which accepts connections and broadcasts messages to all connected clients.
<?php\nuse Ratchet\\Server\\IoServer;\nuse Ratchet\\Http\\HttpServer;\nuse Ratchet\\WebSocket\\WsServer;\nuse Ratchet\\MessageComponentInterface;\nuse Ratchet\\ConnectionInterface;\n\nrequire __DIR__ . '/vendor/autoload.php';\n\nclass Chat implements MessageComponentInterface {\n protected $clients;\n\n public function __construct() {\n $this->clients = new \\SplObjectStorage;\n echo "Server started!\\n";\n }\n\n public function onOpen(ConnectionInterface $conn) {\n $this->clients->attach($conn);\n echo "New connection: {$conn->resourceId}\\n";\n }\n\n public function onMessage(ConnectionInterface $from, $msg) {\n foreach ($this->clients as $client) {\n if ($from !== $client) {\n $client->send($msg);\n }\n }\n echo "Message from {$from->resourceId}: $msg\\n";\n }\n\n public function onClose(ConnectionInterface $conn) {\n $this->clients->detach($conn);\n echo "Connection closed: {$conn->resourceId}\\n";\n }\n\n public function onError(ConnectionInterface $conn, \\Exception $e) {\n echo "Error: {$e->getMessage()}\\n";\n $conn->close();\n }\n}\n\n$server = IoServer::factory(\n new HttpServer(\n new WsServer(\n new Chat()\n )\n ),\n 8080\n);\n\n$server->run();\n\nLet's start the server from the console:
\nphp server.php\n\nThat's it! The server is listening on port 8080 and is ready to accept WebSocket connections. Now