How to Make a Live Chat Script in PHP

In this article, we’ll discuss how you can make a live chat script in PHP. Although there are different ways you could achieve this, we’ll use a socket-based implementation.

If you’re building a community site which involves user engagement, it’s useful to provide a way for users to discuss ideas in real time. When it comes to real-time interaction between users, it’s best to provide a kind of chat-room feature where they can get together and discuss their ideas.

Today, we’re going to discuss how you can implement live chat in your PHP website. As it’s a popular feature, there are a lot of ready-made chat scripts available in the market. You’ll find a mix of both free and premium PHP chat scripts to choose from.

In this article, we’re going to use the Chat Using WebSocket and PHP Socket module, which is built in PHP and is completely open source.

In the next section, we’ll see how to download and configure the Chat Using WebSocket and PHP Socket module.

How to Download and Configure the Chat Using WebSocket and PHP Socket Module

The Chat Using WebSocket and PHP Socket module is available on GitHub, and thus, you can either clone the repository or download the .zip package file.

If you want to clone the Chat Using WebSocket and PHP Socket repository, you can use the following command on your command prompt.

On the other hand, if you want to download the .zip file, you could download it from the official repo.

The Chat-Using-WebSocket-and-PHP-Socket directory contains the package files. You need to place this directory under the document root of your web server so that you can access it via the browser.

Next, the package contains two PHP files, server.php and index.php, and we need to configure the host value in both files. Open both files in your favorite text editor and replace the localhost value with the hostname of your server. Of course, if you’re working on a local machine for testing purposes, you don’t need to change it.

With these changes, we’re done with the configuration of our module. Before we go ahead and see how to run it, we’ll go through the server.php and index.php files to understand how exactly it works in the next section.

How the Chat Using WebSocket and PHP Socket Module Works

The Chat Using WebSocket and PHP Socket module is based on WebSockets. Let’s quickly see what exactly the WebSocket API is:

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. — MDN

Once a browser opens a web socket connection with the web server, it can perform two-way communication with the web server. And thus, it can send data to the web server with the help of the send method, and it can receive data from the web server with the help of the onmessage event handler. So that’s the client-side implementation of WebSockets.

On the server side, we need to use PHP socket functions to open and bind sockets, listen to incoming socket connections, and read and send data to all the available sockets.

Let’s go through the important snippets in both files.

The index.php File

The index.php file is responsible for displaying the chat UI and handling a socket connection with the web server.

Let’s go through the following snippet, which is the most important part in the index.php file.

Firstly, the new WebSocket(wsUri) call opens a socket connection with the web server. Once a socket connection is open, we’ve defined different event handlers to catch different types of events.

Event Handlers

Mainly, the WebSocket object supports four events: onopen, onmessage, onerror, and onclose. Our script has defined event handlers for all these events.

The onopen event handler is used to display a welcome message to users.

Next, the onmessage event handler is used to display messages that are received from the web server. Basically, it parses the JSON data received from the server, prepares the HTML code, and appends it to the chat box.

You can use the onerror event handler to handle errors and display appropriate error messages to users.

Finally, the onclose event handler is used to notify that the connection is closed.

The send Method

If event handlers are used to listen and react to server-side events, the send method allows you to send data from a browser to the web server.

In the index.php file, we’ve defined the send_message function, which is called when users click on the Send button or press the Enter button. The send_message function handles the logic of sending data to the web server.

As you can see, we’ve called the websocket.send method to send data to the web server.

The Server.php File

The server.php file is responsible for listening to incoming socket connections, reading data, and sending it to all the clients. In this section, we’ll discuss important snippets in the server.php file.

The first thing is to create a socket connection by using the socket_create function.

Next, we’ll bind a socket on the specific port and start listening for a connection on that socket.

Also, we’ve initialized the $clients variable, which holds different socket connections from different users.

Finally, there’s the while loop, which is endless, and it does two important things, as explained below.

Firstly, it checks for any new socket connection. If there’s a new socket connection, it’s added to the global $clients variable. It also notifies other clients about this new connection. Basically, other users are notified when a new user joins the chat room.

Next, it loops through all the connected sockets and checks for any incoming data. If there’s any data received on any socket, it reads that data by using the socket_recv function. The received data is in the JSON format, and thus we need to decode it in the first place. Finally, the send_message function is called, which sends this data to all the connected sockets.

The send_message function looks like this:

If any user is disconnected, the following code is responsible for removing the socket client associated with that user from the $clients variable. All connected users are notified about this event as well.

As the while loop is endless, it continuously checks for any new connections and messages, and thus, all users are instantly notified about it.

So that’s the server-side implementation of sockets. In the next section, we’ll see how to run this module.

How to Run the Chat Using WebSocket and PHP Socket Module

Firstly, we’ve got to start the socket server so that it can start listening to incoming connections.

Go ahead and run the server.php file on the command line, as shown in the following snippet. It should start the socket server.

Now, you need to visit the index.php file in your browser. As you’ve placed the Chat-Using-WebSocket-and-PHP-Socket-master directory under the document root, you should be able to access it via https://localhost/Chat-Using-WebSocket-and-PHP-Socket-master/index.php.

You should see the following UI.

chat bot user interface

You can open the http://localhost/Chat-Using-WebSocket-and-PHP-Socket-master/index.php URL from another browser to simulate a multi-user experience. You’ll be notified about the new user connection.

Start messaging in both screens, and you’ll be notified instantly.

chat bot showing messages from two users

As you can see, it’s fairly easy to implement a socket-based PHP chat module on your website. There are other ways as well, like an AJAX-based chat module which continuously polls a server to get new messages from it, but the socket-based implementation is more efficient and doesn’t generate as much traffic to your server, so it is preferred.

Conclusion

Today, we discussed how you can implement live chat in PHP with the help of the Chat Using WebSocket and PHP Socket Module. It’s a socket-based implementation, and we’ve discussed important parts of this module throughout the article.

You can also read about the premium PHP chat scripts available on CodeCanyon.

Leave a comment

Your email address will not be published.