I have a website, in which I use websocket- PHP Ratchet- using class Chat
.
In my website, $_SESSION['user_id']
is well defined. I wish to access this value in the Chat
class.
How can I access this value in the websocket server, whilst this value resides in the website server?
When I do try to access it, I get error: Notice: Undefined variable: _SESSION
(the error line is highlighted in the code)
This is my Chat.php
:
<?php
namespace dealspace_websocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require_once __DIR__ . "/../Model/DBConnection.php";
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
$JSonMsgObject = json_decode($msg, true);
if($JSonMsgObject['type'] === 'updownvote') {
$connection = new \DBConnection();
$allowUpdate = false;
try {
$sql = 'SELECT `voters`
FROM `deals`
WHERE `id` = :id
LIMIT 1';
$stmt = $connection->dbh->prepare($sql);
$stmt->execute(array(
'id' => $JSonMsgObject['deal_data']['dealid']
));
$allowUpdate = $stmt->fetch(\PDO::FETCH_ASSOC);
if($allowUpdate !== false) {
$votersString = $allowUpdate['voters'];
if($votersString !== '')
$votersArray = explode(',', $votersString);
$votersArray[] = $_SESSION['user_id']; // --- Here I try to access --- \\\
$votersString = implode(',', $votersArray);
$allowUpdate = false;
try {
$sql = 'UPDATE `deals`
SET `votes_counter` = :votes_counter, `voters` = :voters
WHERE `id` = :id';
$stmt = $connection->dbh->prepare($sql);
$allowUpdate = $stmt->execute(array(
'votes_counter' => $JSonMsgObject['deal_data']['votes'],
'voters' => $votersString,
'id' => $JSonMsgObject['deal_data']['dealid']
));
if($allowUpdate === true) {
$deal_dataOBJ->dealid = $JSonMsgObject['deal_data']['dealid'];
$deal_dataOBJ->votes = $JSonMsgObject['deal_data']['votes'];
$returnMsg->type = 'updownvote';
$returnMsg->deal_data = $deal_dataOBJ;
foreach($this->clients as $client) {
$client->send(json_encode($returnMsg));
}
}
} catch(\PDOException $e) {}
}
} catch(\PDOException $e) {}
$connection->disconnect();
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
My shell script of the server:
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use dealspace_websocket\Chat;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
?>