Search code examples
phpcookieswebsocketratchet

Getting the clients Cookies from a PHP Ratchet WebSocket Server


I have a PHP Ratchet WebSocket server, running a custom chatroom on my website.

I would like to get the user's cookies when they connect to the server, so that I can get their session data and do something special if they are logged in / have specific permissions / etc.

In other posts (both on StackOverflow and otherwise), it is said that to get session data, you must get the client's cookies, which are supplied in their requests to the web server. The following line of code is meant to do this:

$conn->WebSocket->request->getCookies()

Where $conn is a ConnectionInterface.

My problem is, that when run this simply returns an empty array, even though the DevTools will show that there are indeed cookies.

Why might this not be returning a value?


Solution

  • just in case you're still searching for a solution:

    1.In case your cookies only valid for a specific domain/subdomain - you should establish connection to your WebSocket server over the same address. For example, cookies that only valid for admin.example.com won't be sent to a WebSocket server on your root domain (example.com).

    2.In case your cookies only valid for a secure connection (https://), your WebSocket server should be over a secure connection too (wss://), Which is quite easy to achieve with the latest Ratchet version.

    $webSock = new React\Socket\Server('0.0.0.0:8443', $loop);
    $webSock = new React\Socket\SecureServer($webSock, $loop, [
        'local_cert'        => 'path_to_server_cert',
        'local_pk'          => 'path_to_private_key',
        //'allow_self_signed' => TRUE,
        'verify_peer' => FALSE
    ]);
    

    3.With Ratchet 0.4.x, there is no longer a cookie parser. You can only get it as a raw string and then parse it by yourself.

    Get & Parse cookies with Ratchet 0.4.x :

    $cookiesRaw = $conn->httpRequest->getHeader('Cookie');
    
    if(count($cookiesRaw)) {
        $cookiesArr = \GuzzleHttp\Psr7\parse_header($cookiesRaw)[0]; // Array of cookies
    }