Redis PHP Sessions

PHP sessions are used to stored information about an user session between request, by default PHP uses files to manage these sessions.

Each session is stored on a file, you can check in which folder these files are by checking the parameter session.save_path. To check the parameter session.save_path you can create a php file with phpinfo(); and go to the browser to check this setting, in my case the value for session.save_path is /var/lib/php/sessions.

As an example if you write the following code to use the php sessions to store values and run it in the browser you can see a cookie called PHPSESSID.

$_SESSION["user_id"] = 123;
$_SESSION["setting_name"] = "some setting value";

The cookie PHPSESSID stores a value that corresponds to the file on the server that contains the user session data. In my case when I run this script the value of the cookie PHPSESSID was r1eg0pa6ahbrc5n3sv3mjbs7h9 and if I go to the folder ( /var/lib/php/sessions) containing the php sessions files I find this file sess_r1eg0pa6ahbrc5n3sv3mjbs7h9 witth the content user_id|i:123;setting_name|s:19:"some setting value"; that corresponds to the session data:

:/var/lib/php/sessions# ls
:/var/lib/php/sessions# cat sess_r1eg0pa6ahbrc5n3sv3mjbs7h9 
user_id|i:123;setting_name|s:19:"some setting value";

Now, why should you want to change from PHP sessions files to redis? There are multiple reason for this, but the most obvious one is if you want to use multiple nodes to run your PHP code. If you are using multiple nodes behind a proxy for you php application you cannot store php session files in the local machine since request can hit different nodes that do not contain the session file from the previous node. Basically if you want build scalable applications you can not store state on the local machine so you can use an arbitrary number of nodes to scale.

So if you want use multiple nodes for your php application you can share php sessions by using a shared cache between the nodes, in this case redis.

As the diagram shows, if the php sessions are stored in the nodes is not be possible to send requests to different nodes since the PHP session are local, altough if you use a redis instance you can send the request to any PHP node since all nodes get the PHP session from the shared redis server.

Setup to use redis for PHP sessions

You can use redis for php sessions without almost change any code. First you need to have the php-redis extensions installed, on ubuntu you can install by running sudo apt install php-redis, after that you can enabe redis for php sessions by changing php.ini the settings session.save_handler and session.save_path:

session.save_handler = redis
session.save_path = "tcp://<redis_server_ip>"

Alternatively you can change these settings on the code:

ini_set("session.save_handler", "redis");
ini_set("session.save_path", "tcp://<redis_server_ip>");