title: Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value with PHP
body: <p>I've coded websocket server/client with PHP and it worked for me during 2 years. Now it is not working, saying: <code>Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value</code></p>
  
  <p>My clientside code is essentially this: </p>
  
  <pre><code>socket = new WebSocket("ws://&lt;?= EVENT_SERVER_ADDR ?&gt;:"+EVENT_SERVER_PORT+"&lt;?= EVENT_SERVER_WWW_PATH ?&gt;");
  </code></pre>
  
  <p>PHP serverside code is this:</p>
  
  <pre><code>list ($resource, $host, $connection, $version, $origin, $key, $protocol, $upgrade) = $this-&gt;getheaders ($buffer);
  
  $this-&gt;log ("Handshaking...");
  $reply  = 
      "HTTP/1.1 101 Switching Protocols\r\n" .
      "Upgrade: {$upgrade}\r\n" .
      "Connection: {$connection}\r\n" .
      "Sec-WebSocket-Version: {$version}\r\n" .
      "Sec-WebSocket-Origin: {$origin}\r\n" .
      "Sec-WebSocket-Location: ws://{$host}{$resource}\r\n" .
      "Sec-WebSocket-Accept: " . $this-&gt;calcKey ($key) . "\r\n";
  if ($protocol)
      $reply .= "Sec-WebSocket-Protocol: $protocol\r\n";
  $reply .=   "\r\n";
  
  // Closes the handshake
  socket_write ($user-&gt;socket, $reply, strlen ($reply));
  
  function calcKey ($key) {
      // Constant string as specified in the ietf-hybi-17 draft
      $key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
      $key = sha1 ($key, true);
      // $key = pack ('H*', $key); // should I uncomment this line?
      $key = base64_encode ($key);
  
      return $key;
  }
  
  function getheaders ($buffer) {
      $resource = $host = $connection = $version = $origin = $key = $protocol = $upgrade = null;
  
      preg_match ('#GET (.*?) HTTP#', $buffer, $match) &amp;&amp; $resource = $match[1];
      preg_match ("#Host: (.*?)\r\n#", $buffer, $match) &amp;&amp; $host = $match[1];
      preg_match ("#Connection: (.*?)\r\n#", $buffer, $match) &amp;&amp; $connection = $match[1];
      preg_match ("#Sec-WebSocket-Version: (.*?)\r\n#", $buffer, $match) &amp;&amp; $version = $match[1];
      preg_match ("#Origin: (.*?)\r\n#", $buffer, $match) &amp;&amp; $origin = $match[1];
      preg_match ("#Sec-WebSocket-Key:\s*(.*?)\r\n#", $buffer, $match) &amp;&amp; $key = $match[1];
      preg_match ("#Sec-WebSocket-Protocol:\s*(.*?)\r\n#", $buffer, $match) &amp;&amp; $protocol = $match[1];
      preg_match ("#Upgrade: (.*?)\r\n#", $buffer, $match) &amp;&amp; $upgrade = $match[1];
  
      return array ($resource, $host, $connection, $version, $origin, $key, $protocol, $upgrade);
  }
  </code></pre>
  
  <p>It's funny that those guys just changed the standard without keeping old code functioning and without saying anything online (I really tried to google it very hard). Does anyone know what's my problem?</p>