'Get Cookie Value From HTTP GET Request Header String

I'm trying to get the cookie value from the HTTP get request string. How can I handle the request header string and get the cookie value in it? Is there any method to use or any different solution to handle it?

server.php

<?php
$host = "127.0.0.1";
$port = 20205;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket");
$result = socket_bind($sock, $host, $port) or die("Could not bind to socket");

$result = socket_listen($sock, 3) or die("Could not set up socket listener");

echo "Connection Established\n";

$agents = array();

do {
    $accept = socket_accept($sock) or die("Could not accept incoming connection");
    $header = socket_read($accept, 1024) or die("Could not read input");
    var_dump($header);
    perform_handshaking($header, $accept, $host, $port);
    while (socket_recv($accept, $data, 1024, 0) >= 1) {
        $data = unmask($data);
        $data = json_decode($data);
        $action = $data->action;
        if (isset($data->action) && $action == 'connect') {
            foreach ($agents as $key => $value) {
                if ($key == $agentid && $value != $accept) {
                    socket_close($value);
                    $agents[$key] = $accept;
                }
            }
        }
        break; //exist this loop
    }
} while (true);

This is the way that I'm getting the header string from the HTTP get request.



Solution 1:[1]

This is the method that how I parse the header string.

function perform_handshaking($receved_header, $client_conn, $host, $port)
{
    $headers = array();
    $lines = preg_split("/\r\n/", $receved_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')));
    //hand shaking header
    $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
        "Upgrade: websocket\r\n" .
        "Connection: Upgrade\r\n" .
        "WebSocket-Origin: $host\r\n" .
        "WebSocket-Location: ws://$host:$port/demo/shout.php\r\n" .
        "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_conn, $upgrade, strlen($upgrade));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sezer Can Kaynar