正如其他 StackOverflow 答案所示(没有 Symfony 会话的 Ratchet, 在棘轮 WebSocket 连接中启动会话),没有办法在 Apache 和 Ratchet 进程之间直接共享 $_SESSION 变量。但是,可以启动与 Apache 服务器的会话,然后访问 Ratchet 代码中的会话 cookie。
Apache服务器的index.html启动会话:
<?php
// Get the session ID.
$ses_id = session_id();
if (empty($ses_id)) {
session_start();
$ses_id = session_id();
}
?><!DOCTYPE html> ...
Ratchet MessageComponentInterface 代码访问会话令牌:
public function onMessage(ConnectionInterface $from, $msg) {
$sessionId = $from->WebSocket->request->getCookies()['PHPSESSID'];
# Do stuff with the token...
}
一旦两台服务器都知道用户的会话令牌,它们就可以使用该令牌通过 MySQL 数据库共享信息(这就是我所做的):
# Access session data from a database:
$stmt = $this->mysqli->prepare("SELECT * FROM users WHERE cookie=?");
$stmt->bind_param('s', $sessionId);
$stmt->execute();
$result = $stmt->get_result();
或者,您可以进行更奇特的进程间通信形式:
# Ratchet server:
$opts = array(
'http'=>array(
'method'=>'GET',
'header'=>"Cookie: PHPSESSID=$sessionId\r\n"
)
);
$context = stream_context_create($opts);
$json = file_get_contents('http://localhost:80/get_session_info.php', false, $context);
$session_data = json_decode($json);
# Apache server's get_session_info.php
# Note: restrict access to this path so that remote users can't dump
# their own session data.
echo json_encode($_SESSION);