'Issues with session write/read since changing from server sessions to redis sessions

Our PHP application is showing some strange behaviour since we made the switch from regular server sessions to sessions stored in Redis.

The PHP code hasn't changed, but we notice an issue when writing a session variable which is read in the same function chain.

I'll try to give an example of the code with pseudo code:

  //some code
...
  session_start();
  //now we write the session variable
  $_SESSION[key] = value;
  session_close();
...
  //some other code
  
  return getSomeSpecificValue();
}

function getSomeSpecificValue(){
  //some code
  ...
  session_start();
  $someVar = $_SESSION[key];
  session_close();
  ...
  //some code
  
}

Now the problem is that, since moving to redis sessions, it happens that the variable is empty when reading it, even though we have just written it.

That behaviour did not occur before the move to Redis. Is there a specific race condition or setting we are missing? Or do we need to change the code now?

If anyone can help us out with pointers on where to look, that would be much appreciated. If you need more info, let me know, we have been debugging this issue but can't seem to find a solution for it. Race condition? Data lock? ..

When refreshing the page, the value is not empty anymore, so we are pretty sure it's written to redis, probably on the first attempt (?) :-).



Solution 1:[1]

You have to add Redis Extension on the Web Server e.g for php5

sudo apt-get install php5-redis

Then add the session handler in web server e.g

On LAMP environments:

sudo vim /etc/php5/apache2/php.ini

On LEMP environments:

sudo vim /etc/php5/fpm/php.ini

Add This lines

[label /etc/php5/fpm/php.ini] 
session.save_handler = redis

Then restart web server.

I didn't test the solution but should work. I compiled this answer from this articles https://www.digitalocean.com/community/tutorials/how-to-set-up-a-redis-server-as-a-session-handler-for-php-on-ubuntu-14-04, https://www.cloudways.com/blog/setup-redis-as-session-handler-php/ & https://bestofphp.com/repo/1ma-RedisSessionHandler-php-miscellaneous.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman