×


How to configure Redis as PHP Session Handler on Ubuntu 14 04

Are you trying to configure Redis as PHP Session Handler?

This guide is for you.


Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker.  Redis provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform Redis related tasks and configurations.

In this context, we shall look into 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.


Benefits of using Redis ?

Redis simplifies your code by enabling you to write fewer lines of code to store, access, and use data in your applications. For instance, if your application has data stored in a hashmap, and you want to store that data in a data store – you can simply use the Redis hash data structure to store the data.


More information about 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:

i. A PHP web server running LAMP or LEMP on Ubuntu 14.04 – we will refer to this server as a web

ii. A second, clean Ubuntu 14.04 server where we install Redis – we will refer to this server as Redis.


To implement this successfully, you need proper SSH access to both servers as a regular user with sudo permission.


How does Redis work as PHP Session Handler ?

Here, we will use two distinct servers in this article. Moving forward, let us discuss the steps they use in detail.


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.


i. First, we add the PPA repository by running:

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

Then, we press ENTER to confirm.


ii. Now we need to update the package manager cache:

$ sudo apt-get update

iii. Finally, let us install Redis by running:

$ sudo apt-get install redis-server

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

$ redis-cli ping

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.


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


ii. We run ifconfig to get information about our network interfaces:

$ sudo ifconfig

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)

We look for the inet_addr 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.


iii. Using any command-line editor, we open the file /etc/redis/redis.conf and look for the line that contains the bind definition.


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

$ sudo vim /etc/redis/redis.conf
bind localhost 10.133.14.9

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


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

$ sudo service redis-server restart

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


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


Step 3 – Set a Password for the Redis Server

i. 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:

$ sudo vim /etc/redis/redis.conf

Then, we uncomment the line that contains requirepass, and set a strong password:

requirepass yourverycomplexpasswordhere

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

$ sudo service redis-server restart

Step 4 – Test Redis Connection and Authentication

i. 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>

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.


ii. 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.

To authenticate, we just need to run the AUTH command, providing the same password in the /etc/redis/redis.conf file:

10.133.14.9:6379> AUTH yourverycomplexpasswordhere

Subsequently, we should get an OK as a response. 


iii. Now if we run:

10.133.14.9:6379> keys *

The output should be similar to this:

(empty list or set)


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-cli while we perform the next steps.

We will get back to the redis-cli 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.


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

$ sudo apt-get update

ii. Then we install the php5-redis package:

$ sudo apt-get install php5-redis

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.ini. For a LEMP stack on Ubuntu 14.04, the path is usually /etc/php5/fpm/php.ini.

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().

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

<?php
phpinfo();
?>

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_handler. The default value is files. We should change it to Redis.


On LAMP environments:

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

On LEMP environments:

$ sudo vim /etc/php5/fpm/php.ini
session.save_handler = redis

Now we should find the line containing session.save_path. 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=REDISPASSWORD
session.save_path = "tcp://10.133.14.9:6379?auth=yourverycomplexpasswordhere"

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 restart

On LEMP environments:

$ sudo service php5-fpm restart

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.


i. Initially, we create a file named test.php on the web server and place it inside our document root folder:

$ sudo vim /usr/share/nginx/html/test.php

ii. Subsequently, don’t forget to change /usr/share/nginx/html 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;

iii. Point the browser to http://web/test.php 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.


iv. To verify, go back to the SSH session on the Redis machine, where we previously connected to the Redis service using redis-cli. Fetch the content again with keys *:

10.133.14.9:6379> keys *

And we should get an output similar to this:

1) “PHPREDIS_SESSION:j9rsgtde6st2rqb6lu5u6f4h83”

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 difficult to perform this Redis Configuration process?  We'd be happy to assist you. ]


Conclusion

This article will guide you on the steps to configure Redis as a #PHP Session Handler.  #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. Redis server can be used as a session handler for a PHP application running on Ubuntu and it is a data structure server. 

All of the data is stored in #RAM, so the speed of this system is phenomenal, often performing even better than #Memcached.

Redis is much more than a cache. But unlike a cache, Redis lets you operate on the values. There are 5 data types in Redis - Strings, Sets, Hash, Lists and Sorted Sets. Each data type exposes various #operations.