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

PHP WebSockets

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
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
$socket = stream_socket_server("tcp://127.0.0.1:0", $errno, $errstr);
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
$key = "dGhlIHNhbXBsZSBub25jZQ==";
$magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$accept = base64_encode(sha1($key . $magic, true));
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
function encodeFrame($message) {
    $length = strlen($message);
    return chr(129) . chr($length) . $message;
}
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
$clients = [];
$clients['conn1'] = "socket_resource_1";
$clients['conn2'] = "socket_resource_2";
foreach ($clients as $id => $conn) {
    echo "Broadcasting to $id\n";
}
?>

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.