WebSockets in PHP: Creating Real-Time Applications Without Magic

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

WebSockets in PHP: How to Make Your Site Talk in Real Time

\n\n

Imagine a regular website. You click a button — and wait for the page to refresh. It's like sending a letter by mail: you drop it in the mailbox and hope it arrives. Now imagine you're talking on the phone — you hear the other person immediately. WebSockets are exactly that "phone" for the web. And yes, it works with PHP.

\n\n

Many people think WebSocket is only for Node.js or Python. But PHP, although created for "gluing" HTML, has long outgrown its cradle. Today we'll look at how to build a real-time application in PHP — whether it's a chat, a notification feed, or live analytics. And no crutches.

\n\n

If you've ever tried to make a live chat in PHP using long polling and watched your server crash under 1000 requests per second — this article is for you. WebSockets change the game.

\n\n

What is WebSocket and Why Does PHP Get Along With It?

\n\n

WebSocket is a two-way communication channel between the browser and the server. Unlike HTTP, where the client always initiates the request, here the server can send data to the client on its own. This provides true real-time functionality, not just an imitation.

\n\n

The key difference from long polling (where the client constantly asks "anything new?") is that with WebSocket the connection stays open. You establish it once — and communicate without interruption. The savings in traffic and resources are enormous.

\n\n

PHP, as a language, executes scripts sequentially. But that doesn't stop it from being an excellent server for WebSocket. The secret is in the architecture: we don't run PHP through a web server (Apache/Nginx) for each connection, but use it as a standalone daemon. And that's where libraries come into play.

\n\n

Libraries for WebSocket in PHP: What to Choose?

\n\n

There are two most popular libraries — and both deserve attention:

\n\n
    \n
  • Ratchet — the grandfather of PHP WebSocket. Reliable, proven, but a bit "old-school". It uses an event-driven model based on ReactPHP. Great for simple chats and notifications.
  • \n
  • Swoole — a beast. This isn't just a library, but a whole engine that rewrites the PHP core. It provides asynchronicity, coroutines, and performance close to Go. However, it requires installing an extension on the server.
  • \n
\n\n

For your first introduction, I recommend Ratchet — it's easier to learn and doesn't require editing php.ini. Plus, it works great in combination with ReactPHP, which we'll also touch on today.

\n\n

Writing a Simple WebSocket Server in PHP with Ratchet

\n\n

Let's create a basic echo server. It will receive messages from the client and send them back. This is the classic "Hello, World" for WebSocket.

\n\n

First, install Ratchet via Composer. Open a terminal in the project root:

\n\n
composer require cboden/ratchet
\n\n

Now create a file server.php:

\n\n
<?php\nrequire __DIR__ . '/vendor/autoload.php';\n\nuse Ratchet\\MessageComponentInterface;\nuse Ratchet\\ConnectionInterface;\n\nclass EchoServer implements MessageComponentInterface {\n    public function onOpen(ConnectionInterface $conn) {\n        echo "New connection: {$conn->resourceId}\\n";\n    }\n\n    public function onMessage(ConnectionInterface $from, $msg) {\n        echo "Received: {$msg}\\n";\n        $from->send("Echo: {$msg}");\n    }\n\n    public function onClose(ConnectionInterface $conn) {\n        echo "Connection {$conn->resourceId} closed\\n";\n    }\n\n    public function onError(ConnectionInterface $conn, \\Exception $e) {\n        echo "Error: {$e->getMessage()}\\n";\n        $conn->close();\n    }\n}\n\n// Start the server\nuse Ratchet\\Server\\IoServer;\nuse Ratchet\\Http\\HttpServer;\nuse Ratchet\\WebSocket\\WsServer;\n\                

Blogs

Book Recommendations