Hello friends In this article we will talk about how to use socket in php to make a brilliant chat application. Basically we will use websocket as a bridge to send and recieve messages to php chat server . In general we are using http method to communicate between client and server but in this article we will use socket to connect with server .

Now for communication between client and server we will establish a websocket bridge with protocol ws:// to the page where request will be handled .Then there will be callbacks to handle events between client and server .

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) .

Step 1 : Make a socket server with php

First of all we have to make a socket server to which we will connect our websocket and then handle request accordingly .I am making a mySocket.php file in which I will write code for socket server .

<?php
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);
    socket_write($client,$response);
}


?>

In the above code :

  1. we have created a socket server with socket_create() .
  2. Then we bind that server with our local host and port as defined in define() function i.e., HOST = 127.0.0.1 and PORT = 3469 .
  3. Now we listen for any incoming connection with the help of socket_listen() function .
  4. If any incoming connection is requesting to connect then we accept that connection with the help of socket_accept() function .
  5. Now the incoming connection will send us a header to verify whether the connection is established successfully or not , we have to accept that header and then write a response of headers in order to confirm the incoming connection establishment .
  6. Then we have sent a message hello inside while loop with the help of socket_write() function . Here we are using while loop to continuously send message .

Step 2 : Make a websocket bridge to connect with socket server

Now it’s time to make a web socket bridge to connect with our socket server . I am making a file named as webSocket.html . In this file we will write code for websocket and test our connection with socket server .

<!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">
<title>Web Socket</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>
    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;
    };
</script>
</body>
</html>

In the above code :

  1. We are making a websocket server with the ws:// protocol whose address is pointing to the file which is handling the request for incoming connection i.e., ws://127.0.0.1:3469/mySocket.php with the help of Javascript WebSocket() object.
  2. Now WebSocket() object has a method named as onmessage . This method invokes whenever there is a incoming message from server side . We used that method to recieve data from server side and displayed in our html document.

Now save these two files in same folder and then run the following command

php -q mySocket.php

The above command will create the socket server . Now it’s time to make webSocket bridge .Now open up a new terminal and run .

php -S 127.0.0.1:8000 webSocket.html

The above command will serve the webSocket.html file on 127.0.0.1:8000 . Now open 127.0.0.1:8000 in your browser you will see a hello message in your page just like below image .

how to use socket in php
websocket

If the hello message appears in your html document it means the connection is established successfully . In the next article I will show you how to send and recieve message with the help of websocket .

You can learn more about php socket here.

Next article : how-to-use-socket-in-php-part-2

If you want to learn how to integrate firebase in your web project then you can go through this article

You can visit my profile and follow me on :

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

Twitter : https://twitter.com/anand__346

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

Thank you for reading this article hope you gained some knowledge

see you again in next article , peace out ✌