Building a Real-Time Chat with CodeIgniter and WebSocket: A Practical Guide

A practical guide to building a real-time chat with CodeIgniter 4 and the PHP library Ratchet, covering architecture, the WebSocket server, and the frontend connection.

Building a Real-Time Chat with CodeIgniter and WebSocket: A Practical Guide

If you've ever used an online chat — from WhatsApp Web to a live support widget — you've noticed messages appear instantly, with no need to reload the page. This is possible thanks to WebSockets, a technology that lets the browser and the server exchange data in real time over a single, continuously open connection, instead of opening a new one for every request as plain HTTP does.

In this guide we'll build a simple real-time chat using CodeIgniter, a lightweight and popular PHP framework, paired with a PHP library dedicated to handling WebSocket connections. The goal is to understand the architecture and the key steps, so you can later adapt the project to your own needs.

Why plain HTTP isn't enough for a chat

HTTP, the protocol your browser uses to load web pages, works request by request: the client (the browser) asks the server for something, the server replies, and the connection closes. For a chat app that's awkward: the browser would have to keep asking "any new messages?" every few seconds (a technique called polling), wasting resources and causing noticeable delay.

WebSockets solve this by opening a two-way communication channel that stays active: once the connection is established, both the server and the browser can send messages at any time, without starting a new request from scratch. It's the same principle behind messaging apps, live notifications in admin dashboards, and browser-based multiplayer games.

The architecture: two separate processes

One important detail to understand before starting: CodeIgniter, like most traditional PHP frameworks, is built to handle "classic" HTTP requests through a web server such as Apache or Nginx with PHP-FPM. That kind of PHP execution model isn't designed to keep thousands of persistent connections open — which is exactly what a WebSocket server needs to do.

The most common solution, and the one we'll use here, is to split the two responsibilities:

  • The CodeIgniter application keeps handling everything else: pages, authentication, saving message history to the database, REST APIs.
  • A separate PHP process, launched from the command line and kept running continuously, handles only the WebSocket connections using a dedicated library (in our case Ratchet, one of the most widely used PHP libraries for this purpose).

The two processes talk to each other when needed (for example, to store a message in the database), but remain independent: if the WebSocket server restarts, the main site keeps working normally.

Prerequisites

  • PHP 8.2 or newer: the minimum requirement for recent CodeIgniter 4 releases (version 4.7.4, the latest at the time of writing, is also compatible with PHP 8.5).
  • Composer, the PHP dependency manager, to install CodeIgniter and the required libraries.
  • An existing CodeIgniter 4 project (created with composer create-project codeigniter4/appstarter project-name).
  • The PHP sockets extension enabled, required for the WebSocket server to run.

Step 1: install the WebSocket library

Inside the CodeIgniter project folder, install Ratchet via Composer:

composer require cboden/ratchet

Ratchet is a library that implements the WebSocket protocol in PHP on top of ReactPHP, an asynchronous programming framework: it lets our PHP script handle many connections at once without blocking while waiting on each one.

Step 2: write the chat logic

Let's create a class that implements Ratchet's MessageComponentInterface. This class defines what happens when a user connects, sends a message, or disconnects. A simplified example, saved for instance in app/Libraries/ChatServer.php:

class ChatServer implements MessageComponentInterface {
  protected $clients;
  public function __construct() { $this->clients = new \SplObjectStorage; }
  public function onOpen($conn) { $this->clients->attach($conn); }
  public function onMessage($from, $msg) {
    foreach ($this->clients as $client) {
      if ($from !== $client) { $client->send($msg); }
    }
  }
  public function onClose($conn) { $this->clients->detach($conn); }
  public function onError($conn, $e) { $conn->close(); }
}

In practice: when a message arrives from one user (onMessage), we broadcast it to every other connected user except the sender. This is the base logic of a group chat; from here you can add separate rooms, usernames, private messages, and database persistence.

Step 3: start the WebSocket server

You need a small script to run from the terminal, separate from CodeIgniter's normal request flow — for example chat_server.php at the project root:

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

Running it with php chat_server.php makes the server listen on port 8080, ready to accept WebSocket connections. In production, this script should be kept alive with a tool such as Supervisor, which restarts it automatically after a crash, and placed behind a reverse proxy (Nginx or Apache) that handles the SSL certificate, so you expose the secure wss:// connection instead of plain ws://.

Step 4: connect the frontend

In the CodeIgniter view for the chat page, a few lines of plain JavaScript are enough to connect to the WebSocket server, no external library needed:

const socket = new WebSocket('wss://yoursite.com:8080');
socket.onmessage = (event) => { /* display the received message on the page */ };
document.getElementById('send').onclick = () => { socket.send(messageText); };

From here you can enhance the interface with a CSS framework such as Bootstrap (commonly paired with CodeIgniter) to make the chat look nicer, or hook into the authentication already handled by the CodeIgniter application, passing a token at connection time to verify who's writing.

A ready-made alternative

If you'd rather not write the WebSocket server from scratch, you can look at Composer packages built specifically to integrate with CodeIgniter 4's spark commands, such as takielias/codeigniter4-websocket, which ships a ready structure with callbacks for authentication, rooms, and timers, startable with a dedicated command instead of a separate script. It's handy for quick prototyping, while still relying on the same Ratchet library described above.

Conclusion

Adding a real-time chat to a CodeIgniter project doesn't mean abandoning the framework: it simply means pairing it with a small, dedicated PHP process, built on a library like Ratchet, that handles only the "always connected" part. Once you understand this pattern — a classic application on one side, a persistent WebSocket server on the other — you can extend the same logic to live notifications, auto-updating dashboards, or any other feature that needs instant communication between server and browser.

Official sources

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0