Thursday, 30 November 2017

How to Get Current Location using Google Map Javascript API

Showing client side Google Map using Javascript is a simple task. In this tutorial, we are going to see how to get current location of the user. In this example, I used Google Map Javascript API to display map and get current location of the user. I have created Google API key which is used to access the Google Map Javascript API to request. In a previous tutorial, we have seen how to create Google API key to access Google API to authenticate user via Google OAuth.
Initially, I show the map in a HTML DIV by setting the default options like initial location co-ordinates and zoom level of the map. In this example, I have a button to invoke a javascript function requesting the current location on the click event. After getting the result, the current location is shown with the current latitude and longitude details using a Google Map information window.
Warning: Accessing Google Map Javascript API from the non http origin is deprecated. So you need https origin.

HTML for Map Request Handler

This code shows the HTML for the Map container and button handler used to trigger the JavaScript function to get current location.
<h1>How to Get Current Location using Google Map Javascript API</h1>
<div id="button-layer">
 <button id="btnAction" onClick="locate()">My Current Location</button>
</div>
<div id="map-layer"></div>
And the styles are.
<style>
body {
 font-family :Arial;
}
#map-layer {
 margin: 20px 0px;
 max-width: 600px;
 min-height: 400;
}
#btnAction {
 background: #3878c7;
    padding: 10px 40px;
    border: #3672bb 1px solid;
    border-radius: 2px;
    color: #FFF;
    font-size: 0.9em;
    cursor:pointer;
    display:block;
}
#btnAction:disabled {
    background: #6c99d2;
}
</style>

Requesting Map resource and Plot Current Location using Javascript

In the following Javascript I have defined a callback function for getting the Google Map resource. I specified the name of the callback while accessing Google Map Javascript API with the reference of the API key.
In this script, I have also created a function to get the current location on clicking the “My Current Location” button in the UI. This function creates content to be shown in the information window to show the latitude and longitude co-ordinates of the current Location. 
<script
 src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap"
 async defer></script>
<script type="text/javascript">
var map;
function initMap() {
 var mapLayer = document.getElementById("map-layer");
 var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
 var defaultOptions = { center: centerCoordinates, zoom: 4 }

 map = new google.maps.Map(mapLayer, defaultOptions);
}

function locate(){
 document.getElementById("btnAction").disabled = true;
 document.getElementById("btnAction").innerHTML = "Processing...";
 if ("geolocation" in navigator){
  navigator.geolocation.getCurrentPosition(function(position){ 
   var currentLatitude = position.coords.latitude;
   var currentLongitude = position.coords.longitude;

   var infoWindowHTML = "Latitude: " + currentLatitude + "<br>Longitude: " + currentLongitude;
   var infoWindow = new google.maps.InfoWindow({map: map, content: infoWindowHTML});
   var currentLocation = { lat: currentLatitude, lng: currentLongitude };
   infoWindow.setPosition(currentLocation);
   document.getElementById("btnAction").style.display = 'none';
  });
 }
}
</script>

Get Current Location Output

The following screenshot shows the current location of the user by showing the Latitude and longitude co-ordinates with a Google Map information window.
Download

Add Markers to Show Locations on Google Maps

Google Map Javascript API provides geographical data based on the request sent via the client side script. In a previous tutorial, we have seen how to get the Google Map resource and to plot the current location of the user. In this tutorial, we are going to see how to add markers to show an array of locations on the Google Map.
In this example, I have read locations from a country database containing the number of country names. I iterate the country results and get the latitude and longitude co-ordinate using Google Map GeoCoding Service. Using the location co-ordinates I have added markers to locate the countries on the Map. On mouse over the map marker, I have shown a tooltip with the country name by setting the title parameter.

Read Country Names From the Database

This PHP code connects the database using DBController class and reads the country names into an array. This array of results are used to get the location coordinates using which we can add map markers.
<?php

require("DBController.php");

$dbController = new DBController();

$query = "SELECT * FROM tbl_country";
$countryResult = $dbController->runQuery($query);

?>

Javascript to Add Location Markers on the Google Map

The following Javascript code is used to get the location coordinates for the country name which is retrieved from the database. I iterated the database result and get the latitude and the longitude coordinates of the country on each iteration of the loop using the Google Map GeoCoding service. Then, these location data will be used to plot the country location on the map with a marker. The mouseover event on the marker will show the country name with a tooltip.
<script
  src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap"
  async defer></script>

 <script type="text/javascript">
 var map;
 var geocoder;  

 function initMap() {
  var mapLayer = document.getElementById("map-layer");
  var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
  var defaultOptions = { center: centerCoordinates, zoom: 4 }

  map = new google.maps.Map(mapLayer, defaultOptions);
  geocoder = new google.maps.Geocoder();
  
  <?php
  if (! empty($countryResult)) {
      foreach ($countryResult as $k => $v) {
          ?>  
            geocoder.geocode( { 'address': '<?php echo $countryResult[$k]["country"]; ?>' }, function(LocationResult, status) {
      if (status == google.maps.GeocoderStatus.OK) {
       var latitude = LocationResult[0].geometry.location.lat();
       var longitude = LocationResult[0].geometry.location.lng();
      } 
                 new google.maps.Marker({
                       position: new google.maps.LatLng(latitude, longitude),
                       map: map,
                       title: '<?php echo $countryResult[$k]["country"]; ?>'
                   });
     });
       <?php
      }
  }
  ?>  
 }
 </script>

Add Markers to Show Locations in Google Maps – Output

Download 

Draw Path using Google Maps Javascript API

In this tutorial, we are going to see how to draw a path between multiple locations on a map using Google Maps Javascript API. In a previous tutorial, we have seen example code for adding markers on the map layer. In this example, I add markers to point locations and connect the points by drawing the path between the locations. This path will show the flight plan to cover the locations plotted on the map.
In this code, I have used the Polyline class of the Google Maps API. This class is used to draw pathways on the map layer between the path coordinates. I get the list of countries from the database and compute the location coordinates each country using Google Map GeoCoding service. These locations are pushed into an array that will be passed as the path coordinates parameter of the Polyline class to draw the path.

Accessing Google Map API via Javascript to Draw Path

The following Javascript is used to get the latitude and the longitude coordinates of the countries read from the database. This code is same as we have seen while adding markers on the map in the previous tutorial. These coordinates are pushed into a location array on each iteration.
I have defined a function to call Google Polyline class to draw the path between the location coordinates of the countries. I invoked this function, once all the country results are iterated and their coordinates are stored in an array. This function used the array of path coordinates to draw the path.
<script>
 var map;
 var pathCoordinates = Array();
 function initMap() {
  var countryLength
  var mapLayer = document.getElementById("map-layer");
  var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
  var defaultOptions = {
   center : centerCoordinates,
   zoom : 4
  }
  map = new google.maps.Map(mapLayer, defaultOptions);
  geocoder = new google.maps.Geocoder();
  <?php
            if (! empty($countryResult)) {
            ?>
  countryLength = <?php echo count($countryResult); ?>
  <?php
                foreach ($countryResult as $k => $v) 
                {
            ?>
  geocoder.geocode({
   'address' : '<?php echo $countryResult[$k]["country"]; ?>'
  }, function(LocationResult, status) {
   if (status == google.maps.GeocoderStatus.OK) {
    var latitude = LocationResult[0].geometry.location.lat();
    var longitude = LocationResult[0].geometry.location.lng();
    pathCoordinates.push({
     lat : latitude,
     lng : longitude
    });

    new google.maps.Marker({
     position : new google.maps.LatLng(latitude, longitude),
     map : map,
     title : '<?php echo $countryResult[$k]["country"]; ?>'
    });

    if (countryLength == pathCoordinates.length) {
     drawPath();
    }

   }
  });
  <?php
                }
            }
            ?>
 }
 function drawPath() {
  new google.maps.Polyline({
   path : pathCoordinates,
   geodesic : true,
   strokeColor : '#FF0000',
   strokeOpacity : 1,
   strokeWeight : 4,
   map : map
  });
 }
</script>
<script async defer
 src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap">
 
</script>

Show Path on Google Map using Javascript API – Output

Download

 

Wednesday, 29 November 2017

How to Draw Path on Map using Google Maps Direction API

In this tutorial, we are going to see how to draw the path on map between two locations using Google Map Javascript API. This API provides Direction service to draw route between locations. This direction service requires the start and the endpoint of the route to be drawn. It responds the direction resource which will be rendered on the map layer.
In this example, I have a group of checkboxes showing locations options. On submitting the selected checkbox locations, I formed an array of waypoints to request route path. I am sending the waypoints array to the Google Maps Direction service with the start, endpoint of the route. It responds the direction resource with the status. The response status will be checked and the directions will be set on the map based on the status.

HTML Code to Show Waypoints

The following HTML code contains checkbox input options to show the waypoints. It contains a Draw Path button to trigger the Direction service request with the selected waypoints.
<div class="lbl-way-points">Way Points</div>
    
<div>
<?php
foreach ($countryResult as $k => $v) {
    ?>
  <div class="way-points-option"><input type="checkbox" name="way_points[]" class="way_points" value="<?php echo $countryResult[$k]["country"]; ?>"> <?php echo $countryResult[$k]["country"]; ?></div>
<?php
}
    ?>
<input type="button" id="go" value="Draw Path" class="btn-submit" />
</div>

<div id="map-layer"></div>

Code for initMap and Direction Service Request

The code for initializing map is same as we have seen in the previous tutorials, like getting current location, adding map markers and more. In this code, I formed the waypoints array by using the selected checkbox values. Then, I set the options required for the direction service request, like start and end location and the waypoints. The direction service will respond to the request with the direction resource and the status.
This response status is checked by using a callback function. The direction resource is rendered path on the target map layer based on the response status. If the status is not OK, then I have shown a Javascript alert box to acknowledge the user about the problem occurred while requesting the direction.
<script>
   var map;
 var waypoints
   function initMap() {
        var mapLayer = document.getElementById("map-layer"); 
         var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
      var defaultOptions = { center: centerCoordinates, zoom: 4 }
      map = new google.maps.Map(mapLayer, defaultOptions);

        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        directionsDisplay.setMap(map);

        $("#go").on("click",function() {
             waypoints = Array();
             $('.way_points:checked').each(function() {
                waypoints.push({
                    location: $(this).val(),
                    stopover: true
                });
             });
            var locationCount = waypoints.length;
            if(locationCount > 0) {
                var start = waypoints[0].location;
                var end = waypoints[locationCount-1].location;
                drawPath(directionsService, directionsDisplay,start,end);
            }
        });
        
   }
     function drawPath(directionsService, directionsDisplay,start,end) {
        directionsService.route({
          origin: start,
          destination: end,
          waypoints: waypoints,
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
        }, function(response, status) {
            if (status === 'OK') {
            directionsDisplay.setDirections(response);
            } else {
            window.alert('Problem in showing direction due to ' + status);
            }
        });
  }
</script>

Google Maps Direction Service Request – Output

The following screenshot shows the path among the selected waypoints as populated with the checkboxes.
Download

Multi-language Support to Website using PHP

Creating a Multi-language (multilingual) web page is easy to implement. Multi-language websites are used to increase the volume of users supported for a website. Multi-language support can be done in various ways.
  1. We can have duplicate pages with the same content in required languages.
  2. We can add language configuration (localization) to change the text in a different language.
I prefer to go with the second option described. Instead of duplicating pages, let’s have a common page structure and populate the content based on the language selected by pulling language specific content from lang files and database.

In this tutorial, we are going to create a multilingual page which shows both static and dynamic data. The static data are changed in language basis by using respective language configuration file. The dynamic data are managed by the database columns prefixed with the language code. I will provide multilingual support with two languages English and German. So the database column_name will be en_column_name and de_column_name.

Multi Language HTML Page

This HTML page contains a header showing title and the links ‘English‘, ‘Deutsche‘ for changing the language between English and German, respectively. Also, this page is showing dynamic data from the database. The whole content of this page including static labels and the dynamic database results will be changed based on the language selected.
<div class="language-header">
 <div class="demo-page-title"><?php echo $language["LIST_TITLE"]; ?></div>
 <div class="language-link">
  <a class="language-link-item" href="index.php?lang=en" <?php if($lang == 'en'){?> style="color:#ff9900;" <?php } ?>>English</a> | 
  <a class="language-link-item" href="index.php?lang=de"  <?php if($lang == 'de'){?> style="color:#ff9900;" <?php } ?>>Deutsche</a>
 </div>
</div>
<?php 
 if(!empty($result)){ 
  foreach($result as $k=>$v){
?>
 <div class="demo-row-data">
 <div><strong><?php echo $result[$k][$lang.'_title']; ?></strong></div> 
 <p class="demo-row-description"><?php echo $result[$k][$lang.'_description']; ?>
 </p>
 </div>
<?php  
  } 
 } else {
?>
 <div class="no-result"><?php echo $language["NOTIFY_NO_RESULT"]; ?></div>
<?php 
 } 
?>

Changing the Page content using PHP, Based on Language

In this example, it has two types of data. One is the static text in HTML like the heading or the no-result-notification message. The other is the dynamic data read from the database. In this section, we are going to see the code for changing these two types of data based on the selected language.
On clicking language links, I pass the selected language code in the Querystring. I have created language configuration (localization) files for English and German (lang.en.php, lang.de.php), containing the array of text that used in HTML. Based on the selected language the appropriate configuration file will be included get the text in selected language. The code is,
<?php
 // include language configuration file based on selected language
 $lang = "en";
 if(isset($_GET['lang'])){ 
  $lang = $_GET['lang']; 
 } 
 require_once("lang.".$lang.".php");
?>
...
<div class="demo-page-title"><?php echo $language["LIST_TITLE"]; ?></div>
...
<div class="no-result"><?php echo $language["NOTIFY_NO_RESULT"]; ?></div>
In the PHP code, we connect database and fetch the results. The database contains two type of information title and description. I have separate columns for storing information in multiple languages. The table structure is,



This part of the example is to help you understand, how to do localization using database.
The column name is prefixed by the language code en_ and de_ for storing information in English and German. In the PHP code, we use the selected language code to prepend it with title and description to show the content in the appropriate language. The code is,
<?php 
 if(!empty($result)){ 
  foreach($result as $k=>$v){
?>
 <div class="demo-row-data">
 <div><strong><?php echo $result[$k][$lang.'_title']; ?></strong></div> 
 <p class="demo-row-description"><?php echo $result[$k][$lang.'_description']; ?>
 </p>
 </div>
<?php  
  } 
 }
?>
 Download

Paypal Payment Gateway Integration in PHP

In this tutorial, we are going to see about how to integrate payment gateway in PHP via Paypal. We are going to see an example code in PHP for payment integration. In this example, we are using Paypal sandbox (test) mode to check payment flow before going live.

Paypal Payment Integration Steps

  1. Login / Sign Up with https://developer.paypal.com/
  2. Go to Dashboard -> Sandbox -> Accounts and create test accounts for seller and buyer by selecting Business and Personal respectively.
  3. Login to Sandbox business account and go to My Account -> Profile -> My selling tools
    • Manage PayPal buttons and copy the button code and paste in your page.
    • Manage Website preferences and turn on Auto Return and enter Return URL.
    • Manage Instant payment notifications and select Receive IPN messages (Enabled) and enter Notification URL.

PHP Paypal Payment Gateway Example

In this example, we are having four files to be used in the payment process. These are
  1. index.php – Containing a form with Paypal payment parameters and Buy now button.
  2. payment.php – IPN listener for receiving payment notification and update payment database.
  3. thanks.php – Shows success message after payment.
  4. cancel.php – Acknowledge user if the payment is canceled.

Sending Payment Parameters to Paypal Sandbox

This form contains item_name, item_number, amount, currency and more parameters with Buy now button. We need to copy the Paypal button code from My Account -> Profile -> My selling tools -> PayPal buttons. After clicking this button, the params are sent to Paypal sandbox as mentioned in the form action.
<img src="camera.jpg" />
<h3>Camera <br> $0.01</h3>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
 <input type='hidden' name='business' value='Paypal_Business_TestAccount_Id'>
 <input type='hidden' name='item_name' value='Camera'>
 <input type='hidden' name='item_number' value='CAM#N1'>
 <input type='hidden' name='amount' value='0.01'>
 <input type='hidden' name='no_shipping' value='1'>
 <input type='hidden' name='currency_code' value='USD'>
 <input type='hidden' name='notify_url' value='http://SITE NAME/payment.php'>
 <input type='hidden' name='cancel_return' value='http://SITE NAME/cancel.php'>
 <input type='hidden' name='return' value='http://SITE NAME/success.php'>
 <!-- COPY and PASTE Your Button Code -->
 <input type="hidden" name="cmd" value="_s-xclick">
 <input type="hidden" name="hosted_button_id" value="### COPY FROM BUTTON CODE ###">
 <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_buynow_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
</form>

Instant Payment Notification Listener

In this example, we are having payment.php as IPN listener to receive payment notification. Paypal provides the IPN listener code samples for various languages. We have used paypal_ipn.php and make changes to update Payment database.
...
if (strcmp ($res, "VERIFIED") == 0) {
 // assign posted variables to local variables
 $item_name = $_POST['item_name'];
 $item_number = $_POST['item_number'];
 $payment_status = $_POST['payment_status'];
 $payment_amount = $_POST['mc_gross'];
 $payment_currency = $_POST['mc_currency'];
 $txn_id = $_POST['txn_id'];
 $receiver_email = $_POST['receiver_email'];
 $payer_email = $_POST['payer_email'];
 
 include("dbcontroller.php");
 $db = new DBController();
 
 // check whether the payment_status is Completed
 $isPaymentCompleted = false;
 if($payment_status == "Completed") {
  $isPaymentCompleted = true;
 }
 // check that txn_id has not been previously processed
 $isUniqueTxnId = false; 
 $result = $db->selectQuery("SELECT * FROM payments WHERE txn_id = '$txn_id'");
 if(empty($result)) {
        $isUniqueTxnId = true;
 } 
 // check that receiver_email is your PayPal email
 // check that payment_amount/payment_currency are correct
 if($isPaymentCompleted && $isUniqueTxnId && $payment_amount == "0.01" && $payment_currency == "USD") {
  $payment_id = $db->insertQuery("INSERT INTO payment(item_number, item_name, payment_status, payment_amount, payment_currency, txn_id) VALUES('$item_number', '$item_name', $payment_status, '$payment_amount', '$payment_currency', '$txn_id')");
 }
 // process payment and mark item as paid.
 
 
 if(DEBUG == true) {
  error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
 }
 
}
...
After To set this IPN listener to Paypal go to My Account -> Profile -> My selling tools and select Receive IPN messages (Enabled) and enter this file’s absolute path as Notification URL.


Download

Simple PHP Chat using WebSocket

In this tutorial, we are going to create a simple chat application using WebSocket and PHP socket programming. The WebSocket is used to create a bridge to send or receive messages from the PHP chat server. In the web world, we generally use HTTP request methods to communicate between the client and server side. In this chat example, we use sockets to communicate with the server.
For establishing a socket connection between the client and the server, we use the WebSocket protocol (ws://) to specify the address of the PHP page where the WebSocket handshake is handled. After creating WebSocket there are callbacks to handle the events that occur between the client and the server during the chat process.

Creating WebSocket and Callback Event Handlers

The following script is used to create WebSocket in client side and define callback handlers to handle the different chat events. These handlers give acknowledgments about the connection state, chat messages and the errors if any. The chat message is encoded in JSON format and sent to the server on submit.
<script>  
 function showMessage(messageHTML) {
  $('#chat-box').append(messageHTML);
 }

 $(document).ready(function(){
  var websocket = new WebSocket("ws://localhost:8090/demo/php-socket.php"); 
  websocket.onopen = function(event) { 
   showMessage("<div class='chat-connection-ack'>Connection is established!</div>");  
  }
  websocket.onmessage = function(event) {
   var Data = JSON.parse(event.data);
   showMessage("<div class='"+Data.message_type+"'>"+Data.message+"</div>");
   $('#chat-message').val('');
  };
  
  websocket.onerror = function(event){
   showMessage("<div class='error'>Problem due to some Error</div>");
  };
  websocket.onclose = function(event){
   showMessage("<div class='chat-connection-ack'>Connection Closed</div>");
  }; 
  
  $('#frmChat').on("submit",function(event){
   event.preventDefault();
   $('#chat-user').attr("type","hidden");  
   var messageJSON = {
    chat_user: $('#chat-user').val(),
    chat_message: $('#chat-message').val()
   };
   websocket.send(JSON.stringify(messageJSON));
  });
 });
</script>

PHP Socket Programming for the Chat Application

This PHP code checks for the new socket connection request. If any of a new connection request is found, then it will accept and perform the handshake with the new socket resource. Then, it sends an acknowledgment to the client about the connectivity by sealing the encoded acknowledgment message.
It receives the socket data sent via the existing connections and unseals and decodes it to bundle the received data and send it to the chat client. The handshake, seal, unseal, send functionalities are handled by using the ChatHandler class.
<?php
define('HOST_NAME',"localhost"); 
define('PORT',"8090");
$null = NULL;

require_once("class.chathandler.php");
$chatHandler = new ChatHandler();

$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socketResource, 0, PORT);
socket_listen($socketResource);

$clientSocketArray = array($socketResource);
while (true) {
 $newSocketArray = $clientSocketArray;
 socket_select($newSocketArray, $null, $null, 0, 10);
 
 if (in_array($socketResource, $newSocketArray)) {
  $newSocket = socket_accept($socketResource);
  $clientSocketArray[] = $newSocket;
  
  $header = socket_read($newSocket, 1024);
  $chatHandler->doHandshake($header, $newSocket, HOST_NAME, PORT);
  
  socket_getpeername($newSocket, $client_ip_address);
  $connectionACK = $chatHandler->newConnectionACK($client_ip_address);
  
  $chatHandler->send($connectionACK);
  
  $newSocketIndex = array_search($socketResource, $newSocketArray);
  unset($newSocketArray[$newSocketIndex]);
 }
 
 foreach ($newSocketArray as $newSocketArrayResource) { 
  while(socket_recv($newSocketArrayResource, $socketData, 1024, 0) >= 1){
   $socketMessage = $chatHandler->unseal($socketData);
   $messageObj = json_decode($socketMessage);
   
   $chat_box_message = $chatHandler->createChatBoxMessage($messageObj->chat_user, $messageObj->chat_message);
   $chatHandler->send($chat_box_message);
   break 2;
  }
  
  $socketData = @socket_read($newSocketArrayResource, 1024, PHP_NORMAL_READ);
  if ($socketData === false) { 
   socket_getpeername($newSocketArrayResource, $client_ip_address);
   $connectionACK = $chatHandler->connectionDisconnectACK($client_ip_address);
   $chatHandler->send($connectionACK);
   $newSocketIndex = array_search($newSocketArrayResource, $clientSocketArray);
   unset($clientSocketArray[$newSocketIndex]);   
  }
 }
}
socket_close($socketResource);
?>
and the chat handler class is
<?php
class ChatHandler {
 function send($message) {
  global $clientSocketArray;
  $messageLength = strlen($message);
  foreach($clientSocketArray as $clientSocket)
  {
   @socket_write($clientSocket,$message,$messageLength);
  }
  return true;
 }

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

 function seal($socketData) {
  $b1 = 0x80 | (0x1 & 0x0f);
  $length = strlen($socketData);
  
  if($length <= 125)
   $header = pack('CC', $b1, $length);
  elseif($length > 125 && $length < 65536)
   $header = pack('CCn', $b1, 126, $length);
  elseif($length >= 65536)
   $header = pack('CCNN', $b1, 127, $length);
  return $header.$socketData;
 }

 function doHandshake($received_header,$client_socket_resource, $host_name, $port) {
  $headers = array();
  $lines = preg_split("/\r\n/", $received_header);
  foreach($lines as $line)
  {
   $line = chop($line);
   if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
   {
    $headers[$matches[1]] = $matches[2];
   }
  }

  $secKey = $headers['Sec-WebSocket-Key'];
  $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
  $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
  "Upgrade: websocket\r\n" .
  "Connection: Upgrade\r\n" .
  "WebSocket-Origin: $host_name\r\n" .
  "WebSocket-Location: ws://$host_name:$port/demo/shout.php\r\n".
  "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
  socket_write($client_socket_resource,$buffer,strlen($buffer));
 }
 
 function newConnectionACK($client_ip_address) {
  $message = 'New client ' . $client_ip_address.' joined';
  $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
  $ACK = $this->seal(json_encode($messageArray));
  return $ACK;
 }
 
 function connectionDisconnectACK($client_ip_address) {
  $message = 'Client ' . $client_ip_address.' disconnected';
  $messageArray = array('message'=>$message,'message_type'=>'chat-connection-ack');
  $ACK = $this->seal(json_encode($messageArray));
  return $ACK;
 }
 
 function createChatBoxMessage($chat_user,$chat_box_message) {
  $message = $chat_user . ": <div class='chat-box-message'>" . $chat_box_message . "</div>";
  $messageArray = array('message'=>$message,'message_type'=>'chat-box-html');
  $chatMessage = $this->seal(json_encode($messageArray));
  return $chatMessage;
 }
}
?>

Establish Connection using Command Line

The following image shows the command line screen to establish the connection to start chatting by using this application.

PHP Chat Output

Download