简体   繁体   中英

Using PHP session between apache and websocket server

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 even with session_id() . I failed to get values. 值。 I am doing this in server.php which is suppose to be running with 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.

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:

结果

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM