Redis Server post featured image

Setting Up a Redis Server as a Session Handler for PHP on Ubuntu 20.04

Redis is an open-source in-memory cache and storage system, also referred to as a data structure server. It offers advanced support for several data types, such as hashes, lists, sets, bitmaps, and many more. Because of its excellent performance, Redis finds its popularity in leading industries and top MNCs.

Benefits of Redis

When it comes to speed, there is no match to Redis servers. As a NoSQL database server, it offers a fantastic speed of storing and retrieving data. Besides, Redis has stand-out functionalities that make it seamless to work with different data, including complex ones. The ease of use and sophisticated functionalities of Redis have not only made it stand out but have allowed its increasing standardisation as a mainstream database for corporate and individual users.

Below, we will detail the steps to help you install Redis on Ubuntu 20.04 software. In this tutorial, you will get all the information you need from installing to configuring an external Redis server to be used as a session handler for a PHP application running on Ubuntu 20.04.

Getting Started

To go over the steps, you will need two different database servers (droplets) located in the same data centre with private network enabled. These include:

  • A PHP web server running LAMP and LEMP on Ubuntu 20.04 – we will refer to this server as web.

  • A second, clean Ubuntu 20.04 server where Redis will be installed – we will refer to this server as redis.

Step 1 — Redis Server Installation

Our first step is to install the Redis server on Ubuntu 20.04. Once done, make sure the server is up and running on our redis Droplet.

In this tutorial, we will use Personal Package Archives (PPAs). We highly suggest going with PPAs due to security reasons. Compared to other third-party repositories, PPAs are stable, easy to install, and above all, the repository is designed for Ubuntu users. PPA allows you to get the latest software version available, even for the software you do not find in the official Ubuntu repositories.

Using PPAs from an unauthorised source is a big no-no. Make sure you get the PPAs from authentic and verified sources only. You can add the PPA repository using the command:

Press the Enter key to confirm. After confirmation, we will update the package manager cache using the following command:

Next, we will install Redis using the command:

Once you execute the command, you will have Redis installed on your server. Let’s test the installation using the command:

Once you hit the command, you will see a Redis instance running on the localhost on port 6379. Also, there will be a response named PONG. If you see these, it means you have successfully completed the first step. For a detailed guide on installing and securing Redis, you can take a look at our tutorial How to Install and Secure Redis on Ubuntu 18.04.

Next, let’s move on to the next step- configuring Redis.

Step 2 — Redis Configuration to Accept External Connections

The main goal of configuring Redis is to accept connections coming externally. Why? Because Redis – by default, allows connections only to localhost, and there is a restriction to connect from anywhere else. In simpler terms, you´ll have access from inside the server where you have installed Redis.

First, get a detailed insight on your network interfaces using the ifconfig command:

You will get the output below:

At the eth1 interface, you will find the inet_addr. Here we have 10.133.14.9. We will use this IP address in the upcoming steps to connect the redis server from the web server.

Step 3— Localhost Binding

You are free to use the code editor of your choice (Atom and Visual Studio Code are the most popular ones).

Now, open the file /etc/redis/redis.conf and look for the line that contains the bind definition. You should add your private network IP address to the line:

You may see localhost, instead of 127.0.0.1. No worries, you just need to add your private IP address. Next, restart the Redis service to apply the changes. Use the command below to restart the redis server:

For those users who have installed Redis using the one-click application, you will follow the command mentioned below to restart your server:

Once you restart the redis server, any server present in the same private network will automatically connect to this Redis instance, without the need to do it individually.

Step 4— Redis Server Password Set Up

You can skip this step if you are using the Redis installation for practice or training purposes. However, setting up the password for the redis server is highly recommended if you want to add an extra layer of security to your Redis installation. Let us modify the same configuration file as we did in the previous step. Use the command to edit:

Uncomment the line that contains requirepass, and set a strong password:

Restart the Redis service to reflect the changes you have made. Use the command to restart:

Step 5 — Redis Connection and Authentication Testing

In this step, we will connect to the Redis service from inside the redis machine to make sure all the changes made are working seamlessly as expected. To connect, use the below command:

Here, even if you skip to mention the hostname, it will still run. Our primary aim is to make sure the Redis service accepts the connections seamlessly:

It is possible that you get an AUTH error when trying to access the data from the defined password:

Your output will look similar to this:

To authenticate, run the AUTH command along with the same password you defined in the /etc/redis/redis.conf file:

Next, run the command again:

This time, you will get an OK as a response instead of an error. You will get the output as below:

The output empty list or set means the Redis server is empty. That’s because we have not yet configured the web server as a session handler.

Note: Before we move forward, make sure the SSH session is opened and connected to the redis-cli. In the upcoming steps, we will get back to the redis-cli prompt to verify if the session data was stored properly after we make the necessary changes to the web server.

Step 6 — Redis Extension Installation on the Web Server

The next steps should be executed on the web server. We need to install the PHP Redis extension for PHP to connect to the Redis server.

First, update your package manager cache by running the command:

Next, install the php5-redis package:

You are all set to connect to Redis.

Step 7 — Redis Set-up as the Default Session Handler on the Web Server

PHP has a default session handler. In this step, we will edit the php.ini file on the web server to change the default settings. The php.ini file location depends on the current stack:

  • For a LAMP stack on Ubuntu 20.04, use: /etc/php5/apache2/php.ini.

  • For a LEMP stack on Ubuntu 20.04, the path is usually /etc/php5/fpm/php.ini.

If you are unsure about the location of your main php.ini file, take help of the function phpinfo(). Place the following code in a file named info.php inside your web root directory:

When you are trying to access the script from your browser, search for the row containing “Loaded Configuration File.”You will find the exact location of the main php.ini loaded. Make sure to remove the info.php file as it has all the sensitive content of your environment.

After that, open the php.ini file and look for the line containing session.save_handler. The default value will be files, make sure to change to redis.

On LAMP environments:

On LEMP environments:

Next, uncomment the session.save_path and modify the value to contain the Redis connection string. The content must follow the format below:

Use the password we have set up in Step- 4. In case, you are not using the set password, then provide the parameter auth when configuring Redis. Now, save the file and restart the php service on both environments.

On LAMP environments:

On LEMP environments:

Step 8 — Testing Redis Session Handling

In the final step, we need a PHP script or application to make sure your sessions are now handled by Redis. We will use a simple script that implements a counter – each time you reload the page, the printed number is incremented.

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

Then, change the /usr/share/nginx/html to reflect your document root path:

Next, you have to point your browser to http://web/demo.php to access the script. The program will increment the number every time you reload the page.

Now you will have session information stored on the Redis server. To verify, you have to go back to your SSH session on the redis machine using the redis-cli. Get the content once again with keys *:

You will see the output below:

The output verifies that all the information is stored securely on the redis server. If you want to connect additional web servers, you can follow the same fashion.

Conclusion

Redis is a NoSQL database that allows the storage of numerous unstructured data. Very few databases can compare to the functionalities and simplicity of the redis server. Its increasing popularity continually makes it a must-have with few substitutes compared to its broad features.

To further deepen your knowledge of PHP applications and how to use them, you can take a look at the following tutorials from our blog:

Happy Computing!