With the HTML5 age a lot of new features came to help developers to create amazing apps and amazing user experience, one of these features is called web socket which provides new powers under the HTTP protocol. Web socket resolves the lack of HTTP when we need updating our clients with real time data and also server events regardless of a request.
With the snippet above we already have a code working but also we can specify which protocol we want to use through or connection.
Now that we have the client already is time to concentrate in a key part of the process, the handshake. I would like to recommend if you don't know what is and why we must do that please see this wikipedia article and this from websocket.org.
To perform a handshake we will need the client header and some hash stuff to return those combined to upgrade our header. The key header that we are looking for is the Sec-WebSocket-Key. So let's to our example!
Our header value is uRovscZjNol/umbTt5uKmw== with that we will do the following steps on our server:
The above steps translated to PHP code will be something like the example below
To deeper information go ahead and see the RFC 6455 documentation.
As you saw on this post to create a websocket server from scratch is a tough task, roughly we have a couple of projects that do all the hard work for us. The most common in the PHP world is Ratchet, the documentation is awesome and the repository on github is updated frequently I do recommend Ratchet.