I have searched a lot on the web but didn\'t find a useful clue.
I have a websocket server and a web server running together on my local machine.
I need to
As other StackOverflow answers show (Ratchet without Symfony session, Starting a session within a ratchet websocket connection), there is no way to directly share the $_SESSION variable between Apache and the Ratchet process. It is possible, however, to start a session with the Apache server and then access the session cookie within the Ratchet code.
Apache server's index.html starts the session:
<?php
// Get the session ID.
$ses_id = session_id();
if (empty($ses_id)) {
session_start();
$ses_id = session_id();
}
?><!DOCTYPE html> ...
Ratchet MessageComponentInterface code accesses the session token:
public function onMessage(ConnectionInterface $from, $msg) {
$sessionId = $from->WebSocket->request->getCookies()['PHPSESSID'];
# Do stuff with the token...
}
Once both servers know the user's session token, they can use the token to share information through a MySQL database (which is what I do):
# 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();
Alternatively, you could do a more exotic form of inter-process communication:
# 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);