1. Code
  2. PHP
  3. PHP Scripts

How to Make a Live Chat Script in PHP

Scroll to top
12 min read

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 make and implement live chat in your PHP website. As it’s a popular feature, there are a lot of ready-made chatscripts available in the market. You'll find a mix of both free and premium PHP live chat support 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 PHP 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 PHP and PHP Socket repository, you can use the following command on your command prompt.

1
git clone https://github.com/sanwebe/Chat-Using-WebSocket-and-PHP-Socket.git 

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 PHP 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 PHP 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. Look at a PHP sockets example to see how it actually works. 

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

The index.php File

The index.php file is responsible for displaying the live chat code 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.

1
<script language="javascript" type="text/javascript"> 
2
 //create a new WebSocket object.  
3
 var msgBox = $('#message-box'); 
4
 var wsUri = "ws://localhost:9000/demo/server.php"; 
5
 websocket = new WebSocket(wsUri); 
6
 
7
 websocket.onopen = function(ev) { // connection is open  
8
 msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Demo WebSocket Chat box"!</div>'); //notify user  
9
 } 
10
 // Message received from server  
11
 websocket.onmessage = function(ev) { 
12
 var response = JSON.parse(ev.data); //PHP sends Json data  
13
 
14
 var res_type = response.type; //message type  
15
 var user_message = response.message; //message text  
16
 var user_name = response.name; //user name  
17
 var user_color = response.color; //color  
18
 
19
 switch(res_type){ 
20
 case 'usermsg': 
21
 msgBox.append('<div><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="user_message">' + user_message + '</span></div>'); 
22
 break; 
23
 case 'system': 
24
 msgBox.append('<div style="color:#bbbbbb">' + user_message + '</div>'); 
25
 break; 
26
 } 
27
 msgBox[0].scrollTop = msgBox[0].scrollHeight; //scroll message  
28
 
29
 }; 
30
 
31
 websocket.onerror = function(ev){ msgBox.append('<div class="system_error">Error Occurred - ' + ev.data + '</div>'); }; 
32
 websocket.onclose = function(ev){ msgBox.append('<div class="system_msg">Connection Closed</div>'); }; 
33
 
34
 //Message send button  
35
 $('#send-message').click(function(){ 
36
 send_message(); 
37
 }); 
38
 
39
 //User hits enter key  
40
 $( "#message" ).on( "keydown", function( event ) { 
41
 if(event.which==13){ 
42
 send_message(); 
43
 } 
44
 }); 
45
 
46
 //Send message  
47
 function send_message(){ 
48
 var message_input = $('#message'); //user message text  
49
 var name_input = $('#name'); //user name  
50
 
51
 if(message_input.val() == ""){ //empty name?  
52
 alert("Enter your Name please!"); 
53
 return; 
54
 } 
55
 if(message_input.val() == ""){ //emtpy message?  
56
 alert("Enter Some message Please!"); 
57
 return; 
58
 } 
59
 
60
 //prepare json data  
61
 var msg = { 
62
 message: message_input.val(), 
63
 name: name_input.val(), 
64
 color : '<?php echo $colors[$color_pick]; ?>' 
65
 }; 
66
 //convert and send data to server  
67
 websocket.send(JSON.stringify(msg)); 
68
 message_input.val(''); //reset message input  
69
 } 
70
</script> 

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.

1
websocket.onopen = function(ev) { // connection is open  
2
 msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Demo WebSocket Chat box"!</div>'); //notify user  
3
} 

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.

1
websocket.onmessage = function(ev) { 
2
 var response = JSON.parse(ev.data); //PHP sends Json data  
3
 
4
 var res_type = response.type; //message type  
5
 var user_message = response.message; //message text  
6
 var user_name = response.name; //user name  
7
 var user_color = response.color; //color  
8
 
9
 switch(res_type){ 
10
 case 'usermsg': 
11
 msgBox.append('<div><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="user_message">' + user_message + '</span></div>'); 
12
 break; 
13
 case 'system': 
14
 msgBox.append('<div style="color:#bbbbbb">' + user_message + '</div>'); 
15
 break; 
16
 } 
17
 msgBox[0].scrollTop = msgBox[0].scrollHeight; //scroll message  
18
 
19
}; 

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

1
websocket.onerror = function(ev){ msgBox.append('<div class="system_error">Error Occurred - ' + ev.data + '</div>'); }; 

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

1
websocket.onclose = function(ev){ msgBox.append('<div class="system_msg">Connection Closed</div>'); }; 

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.

1
function send_message(){ 
2
 var message_input = $('#message'); //user message text  
3
 var name_input = $('#name'); //user name  
4
 
5
 if(message_input.val() == ""){ //empty name?  
6
 alert("Enter your Name please!"); 
7
 return; 
8
 } 
9
 if(message_input.val() == ""){ //emtpy message?  
10
 alert("Enter Some message Please!"); 
11
 return; 
12
 } 
13
 
14
 //prepare json data  
15
 var msg = { 
16
 message: message_input.val(), 
17
 name: name_input.val(), 
18
 color : '<?php echo $colors[$color_pick]; ?>' 
19
 }; 
20
 //convert and send data to server  
21
 websocket.send(JSON.stringify(msg)); 
22
 message_input.val(''); //reset message input  
23
} 

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.

1
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 

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

1
socket_bind($socket, 0, $port); 
2
socket_listen($socket); 

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

1
$clients = array($socket); 

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.

1
//check for new socket  
2
if (in_array($socket, $changed)) { 
3
 $socket_new = socket_accept($socket); //accept new socket  
4
 $clients[] = $socket_new; //add socket to client array  
5
 
6
 $header = socket_read($socket_new, 1024); //read data sent by the socket  
7
 perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake  
8
 
9
 socket_getpeername($socket_new, $ip); //get ip address of connected socket  
10
 $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data  
11
 send_message($response); //notify all users about new connection  
12
 
13
 //make room for new socket  
14
 $found_socket = array_search($socket, $changed); 
15
 unset($changed[$found_socket]); 
16
} 

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.

1
//loop through all connected sockets  
2
foreach ($changed as $changed_socket) { 
3
 
4
//check for any incomming data  
5
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1) 
6
{ 
7
$received_text = unmask($buf); //unmask data  
8
$tst_msg = json_decode($received_text, true); //json decode  
9
$user_name = $tst_msg['name']; //sender name  
10
$user_message = $tst_msg['message']; //message text  
11
$user_color = $tst_msg['color']; //color  
12
 
13
//prepare data to be sent to client  
14
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color))); 
15
send_message($response_text); //send data  
16
break 2; //exist this loop  
17
} 
18
 ... 
19
 ... 
20
} 

The send_message function looks like this:

1
function send_message($msg) 
2
{ 
3
 global $clients; 
4
 foreach($clients as $changed_socket) 
5
 { 
6
 @socket_write($changed_socket,$msg,strlen($msg)); 
7
 } 
8
 return true; 
9
} 

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.

1
$buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ); 
2
if ($buf === false) { // check disconnected client  
3
 // remove client for $clients array  
4
 $found_socket = array_search($changed_socket, $clients); 
5
 socket_getpeername($changed_socket, $ip); 
6
 unset($clients[$found_socket]); 
7
 
8
 //notify all users about disconnected connection  
9
 $response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected'))); 
10
 send_message($response); 
11
} 

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.

1
$php -q server.php 

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 interfacechat bot user interfacechat 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 userschat bot showing messages from two userschat 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.

Premade Live Chat PHP Scripts From CodeCanyon

It's never a bad idea to pick up a new skill, like learning how to make a live chat script in PHP. But if you're short on time and need the functionality, check out some of these premade scripts from CodeCanyon:

1. Live Support Chat: Live Chat 3

This download is more than a simple PHP live chat support script. It's user-friendly and easy to install. Just copy the embed code into your site and you're ready. This live chat PHP script (or PHP chatting script) has been optimized for all mobile devices so your site can still be responsive. It also has features like:

  • chatbot functionality
  • operator panel with 20 permission levels
  • transfer customers to other operators
  • professional and exportable statistics
PHP Live Chat Support Script CodePHP Live Chat Support Script CodePHP Live Chat Support Script Code
Live Support Chat - Live Chat 3

2. Connect: Live Video Chat, Conference, Live Class, Meeting, and More

Connect with peers and clients with this comprehensive live chat PHP script (or PHP chatting script). It supports both traditional live text chat and video chatting. This opens it up to a lot of different uses, like conferences, webinars, and more. If your goal is to connect with multiple people online, choose the Connect PHP live chat code.

Connect PHP Live Chat Support ScriptConnect PHP Live Chat Support ScriptConnect PHP Live Chat Support Script
Connect - Live Video Chat, Conference, Live Class, Meeting, Webinar, Whiteboard, File Transfer, Chat

3. Best Support System: Live Web Chat and Ticket Help Centre

Build out a stellar customer support system that includes a live chat PHP script. You can create a knowledge base, ticketing system, and more with this help center download. And of course, customers can chat with you directly in real time with the live chat integration PHP feature.

Best Support System Live Chat PHP ScriptBest Support System Live Chat PHP ScriptBest Support System Live Chat PHP Script
Best Support System-Live Web Chat & Client Desk & Ticket Help Centre

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 live chat PHP scripts available on CodeCanyon.