I have a small websocket server implemented in OpenSwoole. Is there a way to access the users session data? I tried this:
<?php
use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
$server = new Server("0.0.0.0", 9502);
$server->on("Start", function(Server $server)
{
echo "Swoole WebSocket Server is started at http://127.0.0.1:9502\n";
});
$server->on('Open', function(Server $server, Swoole\Http\Request $request)
{
echo "connection open: {$request->fd}\n";
var_dump($request->cookie);
echo "using session id ".$request->cookie['PHPSESSID']."\n";
session_id(trim($request->cookie['PHPSESSID']));
session_start();
echo "user: ".$_SESSION['id_user'];
});
$server->on('Message', function(Server $server, Frame $frame)
{
echo "received message: {$frame->data}\n";
$server->push($frame->fd, json_encode(["hello", time()]));
});
$server->on('Close', function(Server $server, int $fd)
{
echo "connection close: {$fd}\n";
});
$server->on('Disconnect', function(Server $server, int $fd)
{
echo "connection disconnect: {$fd}\n";
});
which gives me this when a client connects:
# php websocket.php
Swoole WebSocket Server is started at http://127.0.0.1:9502
connection open: 1
array(1) {
["PHPSESSID"]=>
string(26) "humr1mg4s26jp5fqkavih6tutf"
}
using session id humr1mg4s26jp5fqkavih6tutf
PHP Warning: session_id(): Session ID cannot be changed after headers have already been sent in websocket.php on line 19
PHP Warning: session_start(): Session cannot be started after headers have already been sent in websocket.php on line 20
PHP Warning: Undefined variable $_SESSION in websocket.php on line 21
PHP Warning: Trying to access array offset on value of type null in websocket.php on line 21
user:
Is there a way to start the users PHP session from the websocket server? The users session itself is started by the website's PHP code hosted on Apache.