I need to access PHP sessions within Node.js so I thought a good idea would be to store the session encoded as JSON with memcached and decode it in Node.js.
I know that I can set session.save_handler = memcached but is there a way to set session.serialize_handler = some_json_handler? or do I have to code it myself using session_set_save_handler?
Any help is very appreciated!
I have got it working with couchbase, at least a proof of concept. You might want to try this https://github.com/msgpack/msgpack-php and the node.js equiv. That should see you right.
The code have is in phalcon so might not be useful for your purposes, but for completeness sake (where $this->_instance() returns a couchbase / memcache instance)
\ini_set('session.serialize_handler', 'msgpack');
and in the session handler
public function read($sessionId){
$data = $this->_instance()->get($this->_getSessionId($sessionId), $this->getOption('lifetime'));
if(!empty($data)){
$data = json_decode($data, true);
return \msgpack_pack($data);
}
return '';
}
public function write($sessionId, $data){
session_decode($data);
$serializedData = json_encode($_SESSION);
$this->_instance()->save($this->_getSessionId($sessionId), $serializedData, $this->getOption('lifetime'));
}
I couldn't get the msgpack to work gracefully with phalcon/couchbase/node in the time I have, as getting the sessions working is only a tiny %, still have to learn node, to write the app to find out if it even does what we want ;)
I use msgpack because I couldn't use session_encode() in my php for some reason, possible due to the MVC implementation
the node JS stuff - it uses express, and is my first attempt at node, so bare that in mind :)
var memcache = require("memcache");
var client = new memcache.Client(11211, "localhost");
client.connect();
client.get("/sessions/"+req.cookies.PHPSESSID, function(error, result){
if(typeof(error)==="undefined"){
var session = JSON.parse(result);
console.log('session : ',session);
res.render('view/name', { title: 'Express' , sessionData: session});
}
I had same requirement. I am using tornado and needed to access php session in python.
Follow this link https://github.com/lboynton/memcached-json-session-save-handler/blob/master/library/Lboy/Session/SaveHandler/Memcached.php.
Hope this helps.