Hello friends , hope you are doing good . In this article we will see how we can send and recieve messages with the help of socket in php . As in my previous article socket in php – part 1 I showed you how to establish a connection with the help of websockets . Now let’s get started implementing a chat application with the help of socket in php .

Requirements :

  1. Php >= 7.0 installed in your system (windows,linux).
  2. php socket library must be enabled in php configuration file (windows).
  3. php socket library must installed (linux).
  4. Path of php must set in environment variable(windows) .

As in previous article we made two files named as mySocket.php and webSocket.html . We tested both these files with the help of these commands .

php -q mySocket.php
//new terminal
php -S webSocket.html

Then open in your browser and you will see hello message there it means connection is established successfully between host and client.

Now we have to make a input in html file to send messages to server . So let’s do it .

Open webSocket.html file in an editor and modify the code like the below code .

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="Description" content="Enter your description here"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="assets/css/style.css">
    <div id="root_div">
        <div class="messages"></div>
        <div class="input_message">
            <input type="text" name="msg" id="msg">
            <button id = "submit_msg">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
    var host = 'ws://';
    var socket = new WebSocket(host);
    socket.onmessage = function(e) {
        document.getElementsByClassName('messages')[0].innerHTML = e.data;
    var button = document.getElementById("submit_msg");
        var data = {
            msg : document.getElementById("msg").value
        document.getElementById("msg").value = "";

In the above code we have implemented a input tag to write messages and send to the server over websocket.

Now for recieving the message on server side we have to modify the mySocket.php file also . So open the file and do some changes like the below code .

function unseal($data) {
    $length = ord($data[1]) & 127;
    if($length == 126) {$masks = substr($data, 4, 4); $data = substr($data, 8);}
    elseif($length == 127) {$masks = substr($data, 10, 4); $data = substr($data, 14);}
    else {$masks = substr($data, 2, 4); $data = substr($data, 6);}
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) {$text .= $data[$i] ^ $masks[$i%4];}
    return $text;

$server = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, HOST, PORT);
$client = socket_accept($server);
$request = socket_read($client,5000);
// echo $request;
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
    sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
$headers = "HTTP/1.1 101 Switching Protocols\r\n";
$headers .= "Upgrade: websocket\r\n";
$headers .= "Connection: Upgrade\r\n";
$headers .= "Sec-WebSocket-Version: 13\r\n";
$headers .= "Sec-WebSocket-Accept: $key\r\n\r\n";
socket_write($client, $headers, strlen($headers));
$msg = "hello";
$response = chr(129) . chr(strlen($msg)) . $msg;
        echo "Message : ";
        $input = trim(fgets(STDIN));
        $response = chr(129) . chr(strlen($input)) . $input;
    if(socket_recv($client,$buffer,2048,0) >= 1){
        $msg = unseal($buffer);
            $msg = json_decode($msg,true);
            if(array_key_exists("msg",$msg) != false){
                echo "Client : ";
                echo "\n";


In the above file we have implemented the code to recieve the messsage from client side over websocket . We had made a function named as unseal() , this function will help us in decoding the message which will recieve from client side over websocket .

Now let’s test our code . So run the following commands

php -q mySocket.php
php -S webSockets.html

and open up in a new tab in your browser you will see an input tag with submit button .

socket in php

and now when you open up the command line interface where you executed the mySocket.php file then you will see something like this which is asking you for a input.

socket in php

Now here you have to type a message and press Enter then your message will send to client i.e., and message will printed in browser . And from browser when you enter a message and click on submit button then your message will send to server i.e., mySocket.php executing in command line interface .

if you have some questions related to these block of code then you can ask me on

Linkedin : https://www.linkedin.com/in/anand-raj-7ba6431a8

Twitter : https://twitter.com/anand__346

Soon I will post practical video on this article on our youtube channel link is given below .

Youtube : https://www.youtube.com/channel/UC1DcIKA0zixS5LOJ1wV1lAg

Note : if you are interested in making your own chat application with the help of firebase , javascript and jquery then enroll the below course .You will get in-depth knowledge of firebase realtime database working with firebase auth.

Udemy Course link : https://www.udemy.com/course/chat-application-with-javascript-jquery-and-firebase/?referralCode=1747A5E2136F2B76D21C