¿How to share sessions in PHP using a Load Balancer?

Viewed 120

I'm trying to make a web app with some user sessions. The tecnologies that I'm using are these: Linux Debian 10 buster. PHP 7.3. MariaDB. Apache 2.4. There's one server acting as a load balancer and two hosts having the web app. The problem here is that I can't get the actual session of a logged user into the web, because of the load balancer creating a new request into the other host, the user needs to log in again into the web. I tried to use an NFS shared folder on the database server to store the sessions but it kind of doesn't work. With the command watch ls /var/sessions_share from the DB server that has the NFS folder I can see the new session files created on the directory but PHP can't get the session. This is the script from one host:

<?php
    session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

    $_SESSION['user'] = "User";

 ?>

And this script is from the other host:

<?php

session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "User logged: ";

if(isset($_SESSION['user'])){
    echo $_SESSION['user'];
}

?>

What should be the best way to perform this operation ? Should I use NFS or is more better and secure another way ? I tried to find some other way to do this, but unfortunately most info is outdated. Thank you for your help.

1 Answers

The best thing you can do is to use something to handle and store the session: if you're using php7 you can use redis, if you are using php5 you can use memcache and if you're oncloud, you can use a solutions like elasticache or the one your provider suggests.

This way, when a server gets a requests, it queries the cache service and retrieve all the data it needs. You can have 1, 10 or 1000 frontend but the session will always be consistent because it's handled by the cache-service.

Don't use sticky session on the load balancer because if you have many people sharing the same public ip address (for example because they are using a proxy) you might end up having having an uneven traffic sharing among your web server.

Related