Advanced Live Group Chat With WebSocket, PHP & jQuery

Read {count} times since 2020

WebSocket is one of the awesomest part of the HTML5 and we developers should experiment with it as it will be the future of client to server communication.

In a recent post, I made a tutorial of live chat with WebSockets and PHP. It was the basic step into websockets. But, I have created another chat which is more advanced that has the capability to upload images as well as record audio from microphone of the user. It’s somewhat like WhatsApp or Facebook Messenger.

For this, you will need a WebSocket server and a web server (localhost).


  • Basic text messaging
  • Anyone can join chat
  • Voice messages
  • Send images
  • Live messaging

This tutorial has two parts, one for setting up the website and the other for setting up the WebSocket server.


The client doesn’t necessarily need to be PHP, because we aren’t gonna process the data here. But, since we are uploading images as well as audio, we should make files in the client site itself to upload these files.


This is the file the users would see to chat :

<!DOCTYPE html>
    <script src="//"></script>
    <script src="//"></script>
    <script src="//"></script>
    <script src="js/time.js"></script>
    <script src="js/chat.js"></script>
    <link href="css/chat.css" rel="stylesheet"/>
    <title>Subin's Blog - Advanced Live Group Chat</title>
    <div id="content">
      <center><h1>Advanced Live Group Chat</h1></center>
      <p><a href="//">Tutorial</a></p>
      <div class="chatWindow">
        <div style="display: none;postion: absolute;">
          <input type="file" id="photoFile" accept="image/*" />
          <audio src="cdn/message.wav" controls="false" id="notification"></audio>
        <div class="users"></div>
        <div class="chatbox">
          <div class="topbar">
            <span id="status" title="Click to Login/Logout">Offline</span>
            <span id="fullscreen" title="Toggle Fullscreen of Chat Box">Fullscreen</span>
          <div class="chat">
            <div class="msgs"></div>
            <form id="msgForm">
              <textarea name="msg" placeholder="Type message here...."></textarea>
              <a class="button" id="voice" title="Click to start recording message"></a>
              <a class="button" id="photo" title="Type in a message and choose image to send"></a>
          <div class="login">
            <p>Type in your name to start chatting !</p>
            <form id="loginForm">
              <input type="text" value="" />

It has a basic layout with some resources loaded in the head.


This file handles the uploads such as images and audios. It will upload the file into a folder named “uploads” in the root directory of the site. So, you should create that folder and set the permission of it to “Read & Write”.

Here is the upload.php file :

  $file = file_get_contents($_FILES['file']['tmp_name']);
  $f = finfo_open();
  $mime_type = finfo_buffer($f, $file, FILEINFO_MIME_TYPE);
  $supported_types = array(
    "audio/x-wav" => "wav",
    "image/png" => "png",
    "image/jpeg" => "jpg",
    "image/pjpeg" => "jpg",
    "image/gif" => "gif"
  $extension = isset($supported_types[$mime_type]) ? $supported_types[$mime_type] : false;
  if($extension !== false){
    $fileName = rand(10000, 65000) . "." . $extension;
    $location = __DIR__ . "/uploads/" . $fileName;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);
    echo $fileName;

You can see that the upload file checks the type of the file and then only it uploads to the server. When it is uploaded, the file name is outputted.


You might have heard about the jQuery Timeago plugin. This file has the plugin with some little modifications. Download it from here.


This is the heart of the chat. All functions related to the chat in the client are processed by this file such as connection to the server, sending messages, uploading files and others…

You can get this file from here.


This file will decorate the chat box. We are adding just a simple design.

You can get this file from here.


There is something else too in this chat. A notification sound. When new messages are retrieved, a sound will be also played. You can download this file from here. Thanks to the open source software Pidgin IM for this sound.


The “assets” folder should contain 3 images :

These files are for the advanced part of the chat. With advancement comes more resources !

WebSocket Server

Let’s move on to the WebSocket Server. This part handles the messages and does all the work to make the chat functional and awesome.


The server has the Database, so create the tables first :

CREATE TABLE `wsAdvancedChat` (
  `user` varchar(20) NOT NULL,
  `msg` varchar(100) NOT NULL,
  `type` varchar(10) NOT NULL,
  `file_name` varchar(100) NOT NULL,
  `posted` datetime NOT NULL

Make sure the database time zone is set to UTC.

Then you should create a configuration file that will provide the credentials to connect to the database :


We are going to use PDO for the connection with MySQL :

$docRoot  = realpath(dirname(__FILE__));

if( !isset($dbh) ){
  $musername = "root";
  $mpassword = "password";
  $hostname  = "";
  $dbname    = "test";
  $port      = "3306";

  $dbh = new PDO("mysql:dbname={$dbname};host={$hostname};port={$port}", $musername, $mpassword);
   * Change The Credentials to connect to database.

We also set the timezone to UTC which is the same for database server and PHP server.

We will use Francium DiffSocket to set up our WebSocket server. In the “server” directory, run :

composer require francium/diffsocket

Once DiffSocket is installed, we should set up the server class and the script to run the server.


This file gets the sent message from server and inserts it into database. It also sends the messages in the database to the users when asked. In fact, this is the server who does everything for its clients.

You can get this file from here.


To add our “Advanced Chat” service and start the server, we must create another file :

require_once __DIR__ . "/config.php";
require_once __DIR__ . "/vendor/autoload.php";

$ip = "";
$port = "8000";
$DS = new Fr\DiffSocket(array(
  "host" => $ip,
  "port" => $port

If you’re going to change the $ip and $port variables, you should also change the WebSocket URL in the “chat.js” file.

When you need to start the server, just run the “run-server.php” file :

php run-server.php

When new users are connected, a message will be shown in the shell that is something like this :

New connection! (29)

Each users connected (clients) will have a unique ID.

Open the website we set up, enter your name and voila !

There you go ! You just set up your own advanced chat system.

Show Comments