I want to pass the session into the Chat class so I can use the user_id as the reference of the user who sent a message. I tried everything but I still had the session value empty.
Server.php ( Ratchet Server)
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
require dirname(__DIR__) . '/vendor/autoload.php';
// Create a session storage
$sessionStorage = new NativeSessionStorage();
// Initialize the session
$session = new Session($sessionStorage);
$session->start();
$chat = new Chat($session);
$server = IoServer::factory(
new HttpServer(
new WsServer(
$chat
)
),
8080
);
$server->run();
Login.php (Controller)
public function validateInput()
{
$errors = [];
$userModel = new Users;
// Create a session storage
$sessionStorage = new NativeSessionStorage();
// Initialize the session
$session = new Session($sessionStorage);
$session->start();
foreach ($_POST as $field => $value) {
if (empty($value)) {
$errors[$field] = ucfirst($field) . " is required!";
}
}
$check = $userModel->first($_POST);
if ($check) {
$email_address = $check->email_address;
$password = $check->password;
if ($_POST["password"] == $password) {
// Set a session variable
$session->set('user_id', $check->user_id);
$session->set('email_address', $email_address);
$session->set('is_logged_in', true);
http_response_code(200);
echo json_encode(['success' => 'Login successful!']);
exit();
}
} else {
$errors[$field] = "Incorrect username or password.";
}
if (!empty($errors)) {
http_response_code(400);
echo json_encode(['errors' => $errors]);
exit();
}
}
Chat.php
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
class Chat implements MessageComponentInterface
{
protected $clients;
protected $session;
protected $model;
public function __construct(Session $session)
{
$this->clients = new \SplObjectStorage;
$this->model = new \Models\Messages;
$this->session = $session;
echo "Server started!";
}
public function onOpen(ConnectionInterface $conn)
{
// Store the new connection to send messages to later
$this->clients->attach($conn);
// Access the user_id from the session
$userId = $this->session->get('user_id');
echo "User ID: $userId\n";
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg)
{
date_default_timezone_set('Asia/Hong_Kong');
$numRecv = count($this->clients) - 1;
echo sprintf(
'Connection %d sending message "%s" to %d other connection%s' . "\n",
$from->resourceId,
$msg,
$numRecv,
$numRecv == 1 ? '' : 's'
);
$userId = $this->session->get('user_id');
$data = json_decode($msg, true);
echo $userId;
$message = [
"user_id" => $data["user_id"],
"message" => $data["message"],
"sent_date" => date("d-m-y h:i:s")
];
$this->model->insert($message);
foreach ($this->clients as $client) {
if ($from == $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn)
{
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
Is there a way to solve this or any approach you recommended when using Ratchet Websocket?
I tried to set a session in the Login Controller in the validateInput method
public function validateInput(){ ... }
But in Chat.php when I use the get function to fetch the user_id but the value is empty when I try to echo it
$userId = $this->session->get('user_id');