Sofia
Bulgaria 1000
8835.1001289.0363
sales@linuxssdvps.com
support@linuxssdvps.com

How to Setup a Redis Server as a Session Handler for PHP on Ubuntu 14.04

How to Setup a Redis Server as a Session Handler for PHP on Ubuntu 14.04

Redis is an (free) open source key-value cache and storage system, also known to as a data structure server for its enhanced support for several data varieties, such as hashes, lists, sets, and bitmaps, amongst some others. It also can handle clustering, which makes it often used for highly-available and scalable environments.

In this guide, we’ll see the way to install and set up an external Redis server to be used as a session handler for a PHP app running on Ubuntu 14.04.

The session handler is in charge for keeping and retrieving data saved into sessions – by default, PHP uses files for that. An external session handler can be used for producing scalable PHP environments behind a load balancer, where all app nodes will be connected to a central server to share session information.
Prerequisites

We will certainly be operating along with two distinct servers in this guide. For safety and effectiveness reasons, it’s important that both Droplets are located in the same datacenter with private networking allowed. This is what you will need:

A PHP web server running LAMP or LEMP on Ubuntu 14.04 – we will refer to this server as web
A second, clean Ubuntu 14.04 server where Redis will be installed – we will refer to this server as redis

You will need proper SSH access to both servers as a regular user with sudo permission.

For the Redis server, you can also use our Redis One-Click Application and skip to Step 2.
Step 1 – Install the Redis Server

The very first thing we need to do is get the Redis server up and running, on our redis Droplet.

We will be using the regular Ubuntu package manager with a trusted PPA repository provided by Chris Lea. This is required to ensure that we get the latest stable version of Redis.

As a general piece of security advice, you should only use PPAs from trusted sources.

1st, add the PPA repository by running:

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

Press ENTER to confirm.

Now you will need to update the package manager cache:

sudo apt-get update

And last but not least, let’s install Redis by running:

sudo apt-get install redis-server

Redis should now be installed on your server. To test the installation, try this command:

redis-cli ping

This will connect to a Redis instance running on localhost on port 6379. You should get a PONG as response.
Step 2 – Configure Redis to Accept External Connections

By default, Redis only permits connections to localhost, which basically usually means you´ll only have access from inside the server where Redis is installed. We really need to change this settings to allow connections coming from different servers on the same private network as the redis server.

The very first thing we need to do is find out the private network IP address of the Redis machine. The following steps should be executed on the redis server.

Perform ifconfig to get info related to your network interfaces:

sudo ifconfig

You must get an output similar to this:

Output
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.123.13.9 Bcast:10.123.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)

Search for the inet_addr assigned to the eth1 interface. In this case, it’s 10.123.13.9 – that is the IP address we will be using later to connect to the redis server from the web server.

With your favorite command line editor, open the file /etc/redis/redis.conf and search for the line that contains the bind definition. You need to add your private network IP address to the line, as follows:

sudo vim /etc/redis/redis.conf

/etc/redis/redis.conf

bind localhost 10.123.13.9

If there is 127.0.0.1 instead of localhost that’s fine; just add your private IP after what’s already there.

Now you simply need to restart the Redis service to apply the changes:

sudo service redis-server restart

In case you installed Redis using our One-click app, the service name will be redis instead of redis-server. To restart it, you should run: sudo service redis restart .

With this switch, any server inside the same private network will also be able to connect to this Redis instance.
Step 3 – Set a Password for the Redis Server

To include an extra layer of safety to your Redis installation, you are encouraged to set a password for accessing the server data. We will edit the same configuration file from the previous step, /etc/redis/redis.conf:

sudo vim /etc/redis/redis.conf

Now, uncomment the line that contains requirepass, and set a strong password:
/etc/redis/redis.conf

requirepass yourverycomplexpasswordhere

Restart the Redis service so the changes take effect:

sudo service redis-server restart

Step 4 – Test Redis Connection and Authentication

To test if all your changes worked as expected, connect to the Redis service from inside the redis machine:

redis-cli -h 10.123.13.9

Output
10.123.13.9:6379>

Despite the fact that it´s not mandatory to specify the host parameter here (because we are connecting from localhost), we did it to ensure the Redis service will accept connections targeted at the private network interface.

If you defined a password and now try to access the data, you should get an AUTH error:

keys *

Output
(error) NOAUTH Authentication required.

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

AUTH yourverycomplexpasswordhere

You should get an OK as response. Now if you run:

keys *

The output should be similar to this:

Output
(empty list or set)

This output simply indicates your Redis server is empty, which is exactly what we expected, because the web server is not yet configured to use this Redis server as a session handler.

Save this SSH session opened and connected to the redis-cli while we perform the next steps – we shall 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 web server.
Step 5 – Install the Redis Extension on the Web Server

The following steps should be performed on the web server. We want to install the PHP Redis extension, otherwise PHP won’t be able to connect to the Redis server.

First, update your package manager cache by running:

sudo apt-get update

Then install the php5-redis package:

sudo apt-get install php5-redis

Your web server must now be able to connect to Redis.
Step 6 – Set Redis as the Default Session Handler on the Web Server

Now we want to edit the php.ini file on the web server to modify the default session handler for PHP. The location of this file will depend on your 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 you are not sure regarding the location of your main php.ini file, an easy way to discover out is by using the function phpinfo(). Just place the next code in a file named info.php inside your web root directory:

<?php
phpinfo();

When accessing the script from your browser, look for the row containing “Loaded Configuration File”, and you should find the exact location of the main php.ini loaded.

Remember to remove the info.php file afterwards, as it contains sensitive info about your environment.

Open your php.ini file and lookup for the line containing session.save_handler. The default value is files. You need to change it to redis.

On LAMP environments:

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

On LEMP environments:

sudo vim /etc/php5/fpm/php.ini

/etc/php5/fpm/php.ini

session.save_handler = redis

Now you must find the line that contains session.save_path. Uncomment it and modify the value so it contains the Redis connection string. The content need to follow this format, all in one line: tcp://IPADDRESS:PORT?auth=REDISPASSWORD
/etc/php5/fpm/php.ini

session.save_path = “tcp://10.123.13.9:6379?auth=yourverycomplexpasswordhere”

You just need to provide the parameter auth if you did set a password when configuring Redis.

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 ensure that your sessions are now managed by Redis, you will need to have a PHP script or application that stores details on sessions. We are going to use a simple script that implements a counter – each time you reload the page, the printed number is incremented.

Create a file named test.php on the web server and place it inside your document root folder:

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

Remember to change /usr/share/nginx/html to reflect your document root path.
/usr/share/nginx/html/test.php

<?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;

Point your web browser to http://web/test.php in order to gain access to the script. It should increment the number each time you reload the page.

Now you need to have session details stored on the Redis server. To confirm, return back to your SSH session on the redis machine, where we previously connected to the Redis service using redis-cli. Fetch the content again with keys *:

keys *

And you must get an output similar to this:

Output
1) “PHPREDIS_SESSION:j9rsgtde6st2rqb6lu5u6f4h83”

This shows that the session details is being stored on the Redis server. You are able to connect additional web servers to the Redis server in a similar way.
Conclusion

Redis is a effective and fast key-value storage service that can also be used as session handler for PHP, enabling scalable PHP environments by offering a distributed system for session storage.


Leave a Reply

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

Themetf