Bobcares

Redis as PHP Session Handler – How to set up on Ubuntu 14.04

by | Jan 4, 2021

Wondering how to configure Redis as PHP Session Handler? We can help you.

Here, at Bobcares, we assist our customers with several Redis queries as part of our Server Management Services.

Today, let us see how to install and configure an external Redis server to be used as a session handler for a PHP application running on Ubuntu 14.04.

 

PHP Session Handler

Sessions provide an effective way to store the data of individual users against a unique session ID. This ID is used to preserve the state information of the users between different page requests.

PHP session handlers are particularly used in user/webserver communicated websites, to validate the state of the users logged-in and logged-out of the application.

The session handler is responsible for storing and retrieving data saved into sessions. By default, PHP uses files for that.

An external session handler can be used for creating scalable PHP environments behind a load balancer, where all application nodes will connect to a central server to share session information.

For security and performance reasons, it is important that both Droplets are located in the same datacenter with private networking enabled.

Before we begin, we need:

  • A PHP web server running LAMP or LEMP on Ubuntu 14.04 – we will refer to this server as a web
  • A second, clean Ubuntu 14.04 server where we install Redis – we will refer to this server as Redis

We will need proper SSH access to both servers as a regular user with

sudoCopy Code
permission.

 

Redis as PHP Session Handler

Our Support Engineers work with two distinct servers in this article. Moving forward, let us discuss the steps they use in detail.

Redis as PHP Session Handler

Step 1 – Install the Redis Server

Initially, we need to get the Redis server up and running, on our Redis server.

We will be using the regular Ubuntu package manager with a trusted PPA repository.  As a general piece of security advice, we should only use PPAs from trusted sources.

First, we add the PPA repository by running:

$ sudo add-apt-repository ppa:chris-lea/redis-serverCopy Code

Then, we press ENTER to confirm.

Now we need to update the package manager cache:

$ sudo apt-get updateCopy Code

Finally, let us install Redis by running:

$ sudo apt-get install redis-serverCopy Code

We have Redis now. To test the installation, we try:

$ redis-cli pingCopy Code

This will connect to a Redis instance running on localhost on port 6379. We should get a PONG as a response.

 

Step 2 – Configure Redis to Accept External Connections

By default, Redis only allows connections to localhost, which basically means we´ll only have access from inside the server. We need to change this configuration to allow connections coming from other servers on the same private network as the Redis server.

The first thing we need to do is find out the private network IP address of the Redis machine.

We run

ifconfigCopy Code
to get information about our network interfaces:

$ sudo ifconfigCopy Code

Our output will be similar to this:

eth0 Link encap:Ethernet HWaddr 04:01:63:7e:a4:01
inet addr:188.166.77.33 Bcast:188.166.127.255 Mask:255.255.192.0
inet6 addr: fe80::601:63ff:fe7e:a401/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3497 errors:0 dropped:0 overruns:0 frame:0
TX packets:3554 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4895060 (4.8 MB) TX bytes:619070 (619.0 KB)

eth1 Link encap:Ethernet HWaddr 04:01:63:7e:a4:02
inet addr:10.133.14.9 Bcast:10.133.255.255 Mask:255.255.0.0
inet6 addr: fe80::601:63ff:fe7e:a402/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:8 errors:0 dropped:0 overruns:0 frame:0
TX packets:7 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:648 (648.0 B) TX bytes:578 (578.0 B)Copy Code

We look for the

inet_addrCopy Code
assigned to the eth1 interface. In this case, it is 10.133.14.9. This is the IP address we will be using later to connect to the Redis server from the webserver.

Using any command-line editor, we open the file

/etc/redis/redis.confCopy Code
and look for the line that contains the bind definition.

We should add our private network IP address to the line, as follows:

$ sudo vim /etc/redis/redis.conf

bind localhost 10.133.14.9Copy Code

If we see 127.0.0.1 instead of localhost that is fine; just add the private IP after what is already there.

Then, we just need to restart the Redis service to apply the changes:

$ sudo service redis-server restartCopy Code

With this change, any server inside the same private network will also be able to connect to this Redis instance.

[Stuck with the configuration? We are available 24*7]

 

Step 3 – Set a Password for the Redis Server

To add an extra layer of security to our Redis installation, we need to set a password to access the server data.

We edit the same configuration file from the previous step,

/etc/redis/redis.conf:Copy Code
$ sudo vim /etc/redis/redis.confCopy Code

Then, we uncomment the line that contains

requirepassCopy Code
, and set a strong password:

requirepass yourverycomplexpasswordhereCopy Code

Finally, we restart the Redis service so the changes take effect:

$ sudo service redis-server restartCopy Code

 

Step 4 – Test Redis Connection and Authentication

To test if all the changes met expectation, we connect to the Redis service from inside the Redis machine:

$ redis-cli -h 10.133.14.9

10.133.14.9:6379>Copy Code

Even though it is not mandatory to specify the host parameter, we do it to make sure the Redis service will accept connections targeted at the private network interface.

If we define a password and try to access the data, we should get an AUTH error:

10.133.14.9:6379> keys *

(error) NOAUTH Authentication required.Copy Code

To authenticate, we just need to run the AUTH command, providing the same password in the

 /etc/redis/redis.conf fileCopy Code
:

10.133.14.9:6379> AUTH yourverycomplexpasswordhereCopy Code

Subsequently, we should get an OK as a response. Now if we run:

10.133.14.9:6379> keys *Copy Code

The output should be similar to this:

(empty list or set)Copy Code

This output just means our Redis server is empty, which is exactly what we expect since the webserver is not yet configured to use this Redis server as a session handler.

Keep this SSH session open and connected to the

redis-cliCopy Code
while we perform the next steps.

We will get back to the

redis-cli Copy Code
prompt to check if the session data is being properly stored after we make the necessary changes to the webserver.

 

Step 5 – Install the Redis Extension on the Web Server

We execute the next steps on the webserver. We need to install the PHP Redis extension, otherwise, PHP will not be able to connect to the Redis server.

First, we update our package manager cache. We run:

$ sudo apt-get updateCopy Code

Then we install the

php5-rediCopy Code
s package:

$ sudo apt-get install php5-redisCopy Code

Our web server should now be able to connect to Redis.

 

Step 6 – Set Redis as the Default Session Handler on the Web Server

Now we need to edit the php.ini file on the webserver to change the default session handler for PHP. The location of this file will depend on our current stack.

For a LAMP stack on Ubuntu 14.04, this is usually

/etc/php5/apache2/php.iniCopy Code
. For a LEMP stack on Ubuntu 14.04, the path is usually
/etc/php5/fpm/php.ini.Copy Code

If we are unsure about the location of the main php.ini file, an easy way to find out is by using the function

phpinfo()Copy Code
.

Just place the following code in a file named info.php inside the webroot directory:

<?php
phpinfo();
?>Copy Code

When accessing the script from the browser, look for the row with “Loaded Configuration File”. We can find the exact location there.

Do not forget to remove the info.php file afterward. It contains sensitive information about our environment.

Then we open the php.ini file and search for the line containing

 session.save_handleCopy Code
r. The default value is
filesCopy Code
. We should change it to Redis.

  • On LAMP environments:
$ sudo vim /etc/php5/apache2/php.iniCopy Code
  • On LEMP environments:
$ sudo vim /etc/php5/fpm/php.ini

session.save_handler = redisCopy Code

Now we should find the line containing

session.save_pathCopy Code
. Uncomment it and change the value so it contains the Redis connection string.

The content should follow this format, all in one line:

tcp://IPADDRESS:PORT?auth=REDISPASSWORDCopy Code
session.save_path = “tcp://10.133.14.9:6379?auth=yourverycomplexpasswordhere”Copy Code

We only need to provide the parameter auth if we did set a password when configuring Redis.

Then, we save the file and restart the PHP service.

  • On LAMP environments:
$ sudo service apache2 restartCopy Code
  • On LEMP environments:
$ sudo service php5-fpm restartCopy Code

 

Step 7 – Test Redis Session Handling

To make sure Redis handles our sessions, we will need a PHP script or application that stores information on sessions.

We are going to use a simple script that implements a counter.

Initially, we create a file named

test.phpCopy Code
on the web server and place it inside our document root folder:

$ sudo vim /usr/share/nginx/html/test.phpCopy Code

Subsequently, don’t forget to change

 /usr/share/nginx/htmCopy Code
l to reflect our document root path.

<?php
//simple counter to test sessions. should increment on each page reload.
session_start();
$count = isset($_SESSION[‘count’]) ? $_SESSION[‘count’] : 1;
echo $count;
$_SESSION[‘count’] = ++$count;Copy Code

Point the browser to

http://web/test.phpCopy Code
in order to access the script. It should increment the number each time we reload the page.

Now we should have session information stored on the Redis server.

To verify, go back to the SSH session on the Redis machine, where we previously connected to the Redis service using

redis-cliCopy Code
. Fetch the content again with keys *:

10.133.14.9:6379> keys *Copy Code

And we should get an output similar to this:

1) “PHPREDIS_SESSION:j9rsgtde6st2rqb6lu5u6f4h83Copy Code

This shows that the session information is being stored on the Redis server. We can connect additional web servers to the Redis server in a similar way.

[Finding it hard to process? We’d be happy to assist you]

 

Conclusion

To conclude, Redis is a powerful and fast key-value storage service. It can also be used as a session handler for PHP, enabling scalable PHP environments. Today we saw how our Support Techs set Redis as a PHP Session Handler.

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Speed issues driving customers away?
We’ve got your back!