PHP, nodeJS and sessions

I have a classic apache server supplying php files and a nodeJS server (with socket.io but without express / connect) used to manage real-time events on this PHP website. Sometimes I need to authenticate clients connecting to the node of the JS server, but this authentication is lost when the user reloads the page, because he also reloads the socket.io client (I store the socket ID on the server, which is lost with every update)
The question is: is there a way to keep the connection in socket.io or a way to bind PHP apache sessions and nodeJS server? Or perhaps a way to store this authentication with cookies (knowing that I have to store sensitive data such as user passwords and keys)?

+6
source share
4 answers

You can use memcached as a session storage handler in PHP . Memcached is a simple keystore accessed through TCP; there is a memcached module available for Node.js.

PHP stores the session in memcached, using the session identifier as the key. Session data (value) stored in memcached is a serialized PHP object with a slight twist. You can learn more about this unusual serialization in the SO question "Parse PHP Session in Javascript" . Fortunately, the NPM module is already there: php-unserialize .


Now for the How-To.

Assumptions

  • memcached is available at 127.0.0.1:11211
  • php.ini (or php.d / memcache.ini) is configured using: session.save_handler='memcached' and session.save_path='tcp://127.0.0.1:11211'
  • you installed the required NPM (2) modules: npm install memcached php-unserialize
  • everything is ok with the CLI

Preparation

First, to get some test data to work, save the following php script ( s.php ):

 <?php session_start(); $_SESSION['some'] = 'thing'; echo session_id()."\n"; print_r($_SESSION); 

Run it with php s.php and it should put stuff in stdout:

 74ibpvem1no6ssros60om3mlo5 Array ( [some] => thing ) 

Ok, now we know the session identifier ( 74ibpvem1no6ssros60om3mlo5 ) and confirmed that the session data is set. To confirm that it is in memcached, you can run memcached-tool 127.0.0.1:11211 dump , which provides a dump of the known key: value pairs, for example, I have two in the test post:

 Dumping memcache contents Number of buckets: 1 Number of items : 3 Dumping bucket 2 - 3 total items add 74ibpvem1no6ssros60om3mlo5 0 1403169638 17 some|s:5:"thing"; add 01kims55ut0ukcko87ufh9dpv5 0 1403168854 17 some|s:5:"thing"; 

So far, we have created 1) the session identifier in php, 2) the saved session data from php to memcached, and 3) confirmed that the data exists through the CLI.

Getting with Node.js

This part is actually very simple. NPMs have already gone through most of the heavy lifting. I prepared a little Node.js script that runs through the CLI, but you get an image:

 var Memcached = require('memcached'); var PHPUnserialize = require('php-unserialize'); var mem = new Memcached('127.0.0.1:11211'); // connect to local memcached var key = process.argv[2]; // get from CLI arg console.log('fetching data with key:',key); mem.get(key,function(err,data) { // fetch by key if ( err ) return console.error(err); // if there was an error if ( data === false ) return console.error('could not retrieve data'); // data is boolean false when the key does not exist console.log('raw data:',data); // show raw data var o = PHPUnserialize.unserializeSession(data); // decode session data console.log('parsed obj:',o); // show unserialized object }); 

Assuming the above is saved as m.js , it can be started using node m.js 74ibpvem1no6ssros60om3mlo5 , which will output something like:

 fetching data with key: 74ibpvem1no6ssros60om3mlo5 raw data: some|s:5:"thing"; parsed obj: { some: 'thing' } 

<strong> Warnings / Gotchas

One of my PHP applications stores some binary data in session values ​​(i.e. is encrypted), but the keys and the normal session object remain intact (as in the example above). In this case, memcached-tool <host:port> dump printed an unsuccessful serialized session string on stdout; I thought it might be isolated from stdout, but I was wrong. When using PHPUnserialize.unserializeSession , he also had a problem with data analysis (with separator | ). I tried several other methods for deserializing sessions on the network, but had no success. I would suggest that memcached maintains the correct data internally since it works with its own PHP session persistence handler, so at the time of this writing, I'm not quite sure if these are deserialization methods or if memcached NPM is just not the right way to receive / interpret data. When using non-binary data, such as ascii or utf-8, it should work as intended.

+7
source

If your project stores a session in a database β€” some do β€” then you might consider using the database as a transmission medium.

If the analysis in your particular case shows a promise, you can use node-mysql (or similar) - see this: link

0
source

Although the thread is old, I would like to recommend what I used for my project. Instead of memcached, you can also use Redis to handle the session. I used phpredis as a php redis client. Instead of storing a session for files, you can save to Redis. Most of the heavy lifting will be performed by Apache. For each request, apache will add session values ​​to cookies. And it reads the session values ​​from each request and checks it.

The setup required to save a php session for redis is also very simple.

session.save_handler = redis session.save_path = "tcp: // host1: 6379? weight = 1, tcp: // host2: 6379? weight = 2 & timeout = 2.5, tcp: // host3: 6379? weight = 2"

What is it. This will force php to save sessions instead of redis instead of redis. It will also move the session that is stored in the files to redraw.

0
source

Source: https://habr.com/ru/post/971026/


All Articles