Please Note: This article is part of our historical archive. Because it was published a while ago, some of the information, links, or context may now be outdated.
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.
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-serverThen, we press ENTER to confirm.
Now we need to update the package manager cache:
$ sudo apt-get updateFinally, let us install Redis by running:
$ sudo apt-get install redis-serverWe have Redis now. To test the installation, we try:
$ redis-cli pingThis 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
to get information about our network interfaces:ifconfig$ sudo ifconfigOur 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
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.inet_addrUsing any command-line editor, we open the file
and look for the line that contains the bind definition./etc/redis/redis.confWe should add our private network IP address to the line, as follows:
$ sudo vim /etc/redis/redis.conf bind localhost 10.133.14.9If 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 restartWith 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.confThen, we uncomment the line that contains
, and set a strong password:requirepassrequirepass yourverycomplexpasswordhereFinally, 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 file10.133.14.9:6379> AUTH yourverycomplexpasswordhereSubsequently, 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
while we perform the next steps.redis-cliWe will get back to the
prompt to check if the session data is being properly stored after we make the necessary changes to the webserver.redis-cli
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 updateThen we install the
s package:php5-redi$ sudo apt-get install php5-redisOur 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
. For a LEMP stack on Ubuntu 14.04, the path is usually/etc/php5/apache2/php.ini/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
r. The default value issession.save_handle. We should change it to Redis.files
- On LAMP environments:
$ sudo vim /etc/php5/apache2/php.ini
- On LEMP environments:
$ sudo vim /etc/php5/fpm/php.ini session.save_handler = redisNow we should find the line containing
. Uncomment it and change the value so it contains the Redis connection string.session.save_pathThe content should follow this format, all in one line:
tcp://IPADDRESS:PORT?auth=REDISPASSWORDsession.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
on the web server and place it inside our document root folder:test.php$ sudo vim /usr/share/nginx/html/test.phpSubsequently, don’t forget to change
l to reflect our document root path./usr/share/nginx/htm<?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
in order to access the script. It should increment the number each time we reload the page.http://web/test.phpNow 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
. Fetch the content again with keys *:redis-cli10.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.