1. Go to this page and download the library: Download axcherednikov/php-websocket library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
axcherednikov / php-websocket example snippets
use WebSocket\Connection;
use WebSocket\MessageType;
use WebSocket\Server;
$server = new Server();
$server->listen('127.0.0.1', 8080);
$server->subprotocols('chat.v1');
$server->onOpen(static function (Connection $connection): void {
echo "open {$connection->id}";
echo $connection->subprotocol ? " ({$connection->subprotocol})\n" : "\n";
});
$server->onMessage(static function (Connection $connection, string $message): void {
$connection->send($message, MessageType::Text);
});
$server->onClose(static function (Connection $connection): void {
echo "close {$connection->id}\n";
});
$server->run();
use WebSocket\MessageType;
use WebSocket\Protocol;
$bytes = Protocol::encode('hello', MessageType::Text);
$frame = Protocol::decode($bytes);
echo $frame->payload; // hello
$server->onHandshake(static function (WebSocket\Request $request): void {
if ($request->header('Origin') !== 'https://app.test') {
throw new WebSocket\HandshakeException(
new WebSocket\HandshakeResponse(403, ['X-Reject' => 'origin'])
);
}
});