Many a time you have to host your website on multiple server such as load balancer to server high traffic website. It is obvious that if i have a load balancer or multiple servers in use, the user’s session is coming from 1 server so if the user is pushed to say server 2 or server 3 then does that mean the user’s session will expire or how to make it work as normal?
I have multi-session checks, so if a user logs-in from a different location it will auto sign them out like we see on bank websites. And this will affect the user journey and create issue to the users? Is there anything I need to do at the database level?
Yes you can do it by using custom session management using MySql or any other database.
Option 1: You can use the common recommended approach suggested by many tech gigs as here https://www.php.net/manual/en/function.session-set-save-handler.php
But sometime, the server configuration doesn’t allow to overwrite the server default session handler, Hence you need to go with some different approach.
Option 2: The way i found the solution.
I created a session handler class using mysql database, create method to start, write, read, unset and destroy the session variable.
Below is the example usage of the same.
Usage Example Just include this file at the top, where you want to manage the session using session data
require_once ‘handleSession.php’; // Make sure to set the Mysql Database credential appropiately
To set session data in DB
Case 1: Set a single session data, pass the key and value in array $cstmSessionHandler->cstm_sess_write(array(‘developer1’=>’1vinod’));
Case 2: To set two dimensional session data, pass the key and value in array as below $newData[‘aaa’][‘ffff’] = ‘1111’; $newData[‘aaa’][‘bbb’] = ‘222’; $cstmSessionHandler->cstm_sess_write($newData);
To read session data
Case 1: To read only a single session variable Pass the session key. $sessionValuesArr = $cstmSessionHandler->cstm_sess_read(‘aaa’);
Case 2: To read all the session which are active. Dont pass any argument $sessionValuesArr = $cstmSessionHandler->cstm_sess_read();
To unset specific session variable $cstmSessionHandler->cstm_sess_unset(‘aaa’);
To destroy all the session variable $cstmSessionHandler->cstm_sess_destroy();
You can download the source code and example from gitlab