Share sessions between php and node

前端 未结 2 1111
执念已碎
执念已碎 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 02:54

    For node (and Express 4.x):

    Start with the example from express-session, but use connect-redis as your session store instead.

    Example code:

    var express = require('express'),
        app = express(),
        cookieParser = require('cookie-parser'),
        session = require('express-session'),
        RedisStore = require('connect-redis')(session);
    
    app.use(express.static(__dirname + '/public'));
    app.use(function(req, res, next) {
      if (req.url.indexOf('favicon') > -1)
        return res.send(404);
      next();
    });
    app.use(cookieParser());
    app.use(session({
      store: new RedisStore({
        // this is the default prefix used by redis-session-php
        prefix: 'session:php:'
      }),
      // use the default PHP session cookie name
      name: 'PHPSESSID',
      secret: 'node.js rules'
    }));
    app.use(function(req, res, next) {
      req.session.nodejs = 'Hello from node.js!';
      res.send(JSON.stringify(req.session, null, '  '));
    });
    
    app.listen(8080);
    

    For PHP:

    Use a redis session handler like redis-session-php.

    Example code:

    
    

    Note: Make sure you use the same prefix(connect-redis)/REDIS_SESSION_PREFIX(redis-session-php) (connect-redis uses 'sess:' and redis-session-php uses 'session:php:' by default) and ttl(connect-redis)/session.gc_maxlifetime(PHP) (and same database if you are using a redis database other than the default) for both redis-session-php and connect-redis.

提交回复
热议问题