1
votes

I am using websocket code from https://github.com/Flynsarmy/PHPWebSocket-Chat

I already have my custom users account with Mysql where user logs in at login.php connected to websocket. Thus I set session/cookie for the particular user. For an example

$_SESSION["user"] = 'xyz';//User is created.

The issue is when I try to use $_SESSION even with session_id(). I failed to get $_SESSION values. I am doing this in server.php which is suppose to be running with php server.php command. I try code below.

session_id("lsjdfjl');
@session_start();
$user = $_SESSION["user"];

And I get error message saying undefine index ...

Is there any alternative way to combine above Websocket server with custom user datab ase and create seperate chatroom for different logged in users. For example FB chat/gmail chat system.

2

2 Answers

3
votes

The accepted answer isn't really accurate.

You can use the same session data - see here:

https://stackoverflow.com/a/49802049/1274820

I will post code and image here too for posterity and to avoid link rot:

var cookie = require('cookie');
var fs = require('fs');
var phpUnserialize = require('php-unserialize');

//This should point to your php session directory.
//My php.ini says session.save_path = "${US_ROOTF}/tmp"
var SESS_PATH = "C:/SomeDirectory/WhereYourPHPIs/tmp/";

io.on('connection', function(socket) {
    //I just check if cookies are a string - may be better method
    if(typeof socket.handshake.headers.cookie === "string") {
        var sid = cookie.parse(socket.handshake.headers.cookie);
        if(typeof sid.PHPSESSID === "undefined") {
          console.log("Undefined PHPSESSID");
        }
        else {
            console.log("PHP Session ID: " + sid.PHPSESSID);
            fs.readFile(SESS_PATH + "sess_" + sid.PHPSESSID, 'utf-8', function(err,data) {
                if(!err) {
                    console.log("Session Data:");
                    var sd = phpUnserialize.unserializeSession(data);
                    console.log(sd);
                }
                else {
                   console.log(err);
                }
            });
        }
    }
}

Results:

Results

1
votes

You can't use same session.

You can't use session for websocket connection at all.

Websocket connection is a separate connection, on different port, so your main session is not available there.

You need to read about token-based websocket auth. Here is some info to start from https://auth0.com/blog/2014/01/15/auth-with-socket-io/