【问题标题】:Get Cookie Value From HTTP GET Request Header String从 HTTP GET 请求标头字符串中获取 Cookie 值
【发布时间】:2022-02-05 17:46:53
【问题描述】:

我正在尝试从 HTTP 获取请求字符串中获取 cookie 值。如何处理请求标头字符串并获取其中的 cookie 值?有什么方法可以使用或者有什么不同的解决方案来处理吗?

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

这是我从 HTTP 获取请求中获取标头字符串的方式。

【问题讨论】:

  • 你为什么使用json_decode()? HTTP 协议不使用 JSON 格式。
  • 需要解析headers,找到Cookie: header。
  • 你为什么要在 PHP 中实现 HTTP 服务器?
  • @Barmar 我正在使用 json_decode() 因为客户端接收到的消息格式设置为带有 javascript 的 JSON。
  • 您的代码似乎假设整个标题将在单个socket_read() 中读取。这不是一个好的假设。

标签: php sockets cookies websocket http-headers


【解决方案1】:

这是我解析标题字符串的方法。

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));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多