skip to Main Content

I have a simple PHP websocket server

Here is the full code : https://gist.github.com/hack4mer/e40094001d16c75fe5ae8347ebffccb7

while (true) {

$changed = $clients;
socket_select($changed, $null, $null, 0, 10);

//check for new socket
if (in_array($socket, $changed)) {
    $socket_new = socket_accept($socket); //accpet new socket
    $clients[] = $socket_new; //add socket to client array

   //THIS DOES NOT WORK
   print_r($_SERVER);
   die();

}

In the browser’s network tab, I can confirm the following request:

Request URL: ws://localhost:12345/
Provisional headers are shown
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,hi;q=0.8,ms;q=0.7
Cache-Control: no-cache
Connection: Upgrade
Host: localhost:12345
Origin: http://localhost

However am not able to access these request headers in my script.

My aim is to restrict access of the WebSocket to only few hosts

2

Answers


  1. Chosen as BEST ANSWER

    I solved this issue by doing the header checking before the handshaking.

    Full code : https://gist.github.com/hack4mer/e40094001d16c75fe5ae8347ebffccb7

    function perform_handshaking($receved_header,$client_conn, $host, $port)
    {
    $headers = array();
    $lines = preg_split("/rn/", $receved_header);
    foreach($lines as $line)
    {
        $line = chop($line);
        if(preg_match('/A(S+): (.*)z/', $line, $matches))
        {
            $headers[$matches[1]] = $matches[2];
        }
    }
    
     //HEADERS AVAILABLE HERE -> $headers
    
    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshakern" .
    "Upgrade: websocketrn" .
    "Connection: Upgradern" .
    "WebSocket-Origin: $hostrn" .
    "WebSocket-Location: ws://$host:$port/demo/shout.phprn".
    "Sec-WebSocket-Accept:$secAcceptrnrn";
    socket_write($client_conn,$upgrade,strlen($upgrade));
    }
    

  2. You will have to buffer the data, at least until the headers are done (CRLF).

    Have a look at react/socket.
    It is very easy to use non-blocking sockets with that.

    To implement the websocket protocol, have a look at ratchetphp/RFC6455.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search