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 127.0.0.1:8000 webSocket.html

Then open 127.0.0.1:8000 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">
<head>
<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">
<title>Title</title>
</head>
<body>
    <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>
        </div>
    </div>
<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>
<script>
    var host = 'ws://127.0.0.1:3469/mySocket.php';
    var socket = new WebSocket(host);
    socket.onmessage = function(e) {
        document.getElementsByClassName('messages')[0].innerHTML = e.data;
    };
    var button = document.getElementById("submit_msg");
    button.addEventListener("click",function(e){
        e.preventDefault();
        var data = {
            msg : document.getElementById("msg").value
        }
        document.getElementById("msg").value = "";
        socket.send(JSON.stringify(data));
    })
</script>
</body>
</html>

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 .

<?php
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;
}
define("HOST","127.0.0.1");
define("PORT","3469");

$server = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($server, HOST, PORT);
socket_listen($server,3);
$client = socket_accept($server);
$request = socket_read($client,5000);
// echo $request;
preg_match('#Sec-WebSocket-Key: (.*)\r\n#', $request, $matches);
$key = base64_encode(pack(
    'H*',
    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;
while(1){
    sleep(1);
    if($client){
        echo "Message : ";
        $input = trim(fgets(STDIN));
        $response = chr(129) . chr(strlen($input)) . $input;
        socket_write($client,$response);
    }else{
        die();
    }
    if(socket_recv($client,$buffer,2048,0) >= 1){
        $msg = unseal($buffer);
        if($msg){
            $msg = json_decode($msg,true);
            if(array_key_exists("msg",$msg) != false){
                echo "Client : ";
                print_r($msg["msg"]);
                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 127.0.0.1:8000 webSockets.html

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

socket in php
webSockets.html

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
mySocket.php

Now here you have to type a message and press Enter then your message will send to client i.e., 127.0.0.1:8000 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