Bobcares

For every $500 you spend, we will provide you with a $500 credit on your account*

BLACK FRIDAY SPECIAL EXTENSION

*The maximum is $4000 in credits, Offer valid till December 6th, 2024, New Customers Only, Credit will be applied after purchase and expires after six (6) months

For every $500 you spend, we will provide you with a $500 credit on your account*

BLACK FRIDAY SPECIAL EXTENSION

*The maximum is $4000 in credits, Offer valid till December 6th, 2024, New Customers Only, Credit will be applied after purchase and expires after six (6) months

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 sudo 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-server

Then, we press ENTER to confirm.

Now we need to update the package manager cache:

$ sudo apt-get update

Finally, let us install Redis by running:

$ sudo apt-get install redis-server

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.

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

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.

Using any command-line editor, we open the file /etc/redis/redis.conf 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.9

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 restart

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:

$ sudo vim /etc/redis/redis.conf

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

requirepass yourverycomplexpasswordhere

Finally, we 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 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.

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

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

$ sudo apt-get update

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.

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

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;

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.

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

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

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

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

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