Share sessions between php and node

前端 未结 2 1112
执念已碎
执念已碎 2020-12-03 02:19

Is there an recent guide (or example code) to using node, express, and redis/predis to share PHPSESSID?

I\'ve found several tutorials 1-2 years old and they are all

2条回答
  •  春和景丽
    2020-12-03 03:05

    I just wanted to offer an alternate solution here that doesn't require redis and I've been using for a couple years (cross-posting from another answer):

    This requires the following:

    npm install cookie

    npm install php-unserialize

    This solution uses the session files on the machine - you shouldn't have to change this line.

    session.save_handler = files

    ^ Should be like this in your php.ini file (default).

    Here is the super simple code to retrieve the session data:

    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:

    Authenticate user for socket.io/nodejs

提交回复
热议问题