← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 6 of 10

PHP WebSockets

WebSockets keep an open line between the browser and the server, like a phone call instead of sending letters. Both sides can talk any time, which is great for chat and live updates.

Introduction to WebSockets

WebSockets keep a single connection open between browser and server for as long as needed, allowing both sides to push data at any time -- unlike HTTP, where the server can only respond after the client asks.

Example: Introduction to WebSockets

php
<?php
// Print "WebSockets keep one connection open so either side can push data anytime" to the output
echo "WebSockets keep one connection open so either side can push data anytime";
?>

Socket Server Initialization

stream_socket_server() opens a raw socket that listens for incoming connections, forming the low-level foundation a PHP WebSocket server is built on top of.

Example: Socket Server Initialization

php
<?php
// Declare `$socket`, set to `stream_socket_server("tcp://127.0.0.1:0", $errno, $errstr)`
$socket = stream_socket_server("tcp://127.0.0.1:0", $errno, $errstr);
// Print `$socket ? "Socket server listening" : "Failed: $errstr"` to the output
echo $socket ? "Socket server listening" : "Failed: $errstr";
if ($socket) fclose($socket);
?>

Handling Handshake Requests

Establishing a WebSocket connection requires a specific handshake: the server takes the client's Sec-WebSocket-Key, combines it with a fixed magic string, hashes it, and returns the result to confirm the upgrade.

Example: Handling Handshake Requests

php
<?php
// Declare `$key`, set to "dGhlIHNhbXBsZSBub25jZQ=="
$key = "dGhlIHNhbXBsZSBub25jZQ==";
// Declare `$magic`, set to "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
$magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// Declare `$accept`, set to `base64_encode(sha1($key . $magic, true))`
$accept = base64_encode(sha1($key . $magic, true));
// Print `$accept` to the output
echo $accept;
?>

Formatting Data Frames

WebSocket messages travel as binary-framed packets rather than plain text, so outgoing strings must be wrapped in the correct frame format before being written to the socket.

Example: Formatting Data Frames

php
<?php
// Define the function `encodeFrame` taking `$message`
function encodeFrame($message) {
    // Declare `$length`, set to `strlen($message)`
    $length = strlen($message);
    // Return `chr(129) . chr($length) . $message` from this function
    return chr(129) . chr($length) . $message;
}
// Print `bin2hex(encodeFrame("hi"))` to the output
echo bin2hex(encodeFrame("hi"));
?>

Client Connection Manager

Because a WebSocket server may serve many clients at once, keeping open connections in an array registry lets you broadcast to all of them, message a specific one, or clean up connections that have disconnected.

Example: Client Connection Manager

php
<?php
// Declare `$clients` as an empty array
$clients = [];
// Set `$clients['conn1']` to "socket_resource_1"
$clients['conn1'] = "socket_resource_1";
// Set `$clients['conn2']` to "socket_resource_2"
$clients['conn2'] = "socket_resource_2";
// Loop over `$clients`, binding each item to `$id => $conn`
foreach ($clients as $id => $conn) {
    // Print "Broadcasting to $id\n" to the output
    echo "Broadcasting to $id\n";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Running a PHP WebSocket server under a normal web server request, when it needs a long-running CLI process.
  2. Skipping the handshake header check, so browsers do not accept the connection.
  3. Forgetting to mask or unmask frames correctly in the WebSocket protocol.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.