Piet Piet - 11 months ago 93
PHP Question

PHP Cookies are not set by websocket handshake

I created a PHP websocket server and connected with a webbrowser to it. Everything works fine. Now I want to sent some cookie information to the websocket server, but the cookies and never send with the headers. I really don't have any idea why the cookies aren't included in the request headers. (The cookie is set and not empty when echo'ing with php in index.php)

This is the request and response header


GET ws:// HTTP/1.1
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://localhost
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Sec-WebSocket-Key: 2nR9SZYdLOG32fpV6eJ/wA==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits


HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: QecMAdsem/PYww1pYkyjD+79OmM=


// do handyshake: (hybi-10)
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$response = "HTTP/1.1 101 Switching Protocols\r\n";
$response.= "Upgrade: websocket\r\n";
$response.= "Connection: Upgrade\r\n";
$response.= "Sec-WebSocket-Accept: " . $secAccept . "\r\n";

Way of connecting to server in client (javascript)

var socket = new WebSocket('ws://');

Answer Source

You are loading your page from localhost, but connecting your WebSocket to
Those two are considered two different domains, so they don't share cookies.

You need to connect your WebSocket as:

var socket = new WebSocket('ws://localhost:9000/chat');

Or better, if you don't hardcode the hostname:

var socket = new WebSocket('ws://'+location.hostname+':9000/chat');