PHP WebSockets
In this page:
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
echo "WebSockets keep one connection open so either side can push data anytime";
?>
Login to try C/C++/Java/PHP code in the editor
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
$socket = stream_socket_server("tcp://127.0.0.1:0", $errno, $errstr);
echo $socket ? "Socket server listening" : "Failed: $errstr";
if ($socket) fclose($socket);
?>
Login to try C/C++/Java/PHP code in the editor
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
$key = "dGhlIHNhbXBsZSBub25jZQ==";
$magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$accept = base64_encode(sha1($key . $magic, true));
echo $accept;
?>
Login to try C/C++/Java/PHP code in the editor
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
function encodeFrame($message) {
$length = strlen($message);
return chr(129) . chr($length) . $message;
}
echo bin2hex(encodeFrame("hi"));
?>
Login to try C/C++/Java/PHP code in the editor
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
$clients = [];
$clients['conn1'] = "socket_resource_1";
$clients['conn2'] = "socket_resource_2";
foreach ($clients as $id => $conn) {
echo "Broadcasting to $id\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: