Using Redis for PHP Session Storage

Posted on in System Administration

cover image for article

I have written previously regarding using Redis for Magento session storage. You can get the same benefits of using Redis for session storage (reduced disk I/O, automatic key eviction) for any PHP application by making a quick change to a couple of settings in your php.ini. I assume you already have a Redis server up and listening on port 6379 of localhost.

You'll need to install the PHP Redis extension. The name of the package is going to depend on your distribution. I use Ubuntu, so the name of the package is php5-redis. This should work fine for other Debian-based distributions. (Red Hat-based distributions use php-pecl-redis, I believe.)

Once PHP Redis extension is installed, the gist below contains a diff of what changes need to be made in php.ini. Really, it is just a matter of tweaking two settings.

--- php.ini~ 2015-11-10 10:19:16.510485456 -0600
+++ php.ini 2015-11-10 10:20:10.830483477 -0600
@@ -1324,7 +1324,7 @@
 [Session]
 ; Handler used to store/retrieve data.
 ; http://php.net/session.save-handler
-session.save_handler = files
+session.save_handler = redis

 ; Argument passed to save_handler.  In the case of files, this is the path
 ; where data files are stored. Note: Windows users have to change this
@@ -1353,7 +1353,7 @@
 ; where MODE is the octal representation of the mode. Note that this
 ; does not overwrite the process's umask.
 ; http://php.net/session.save-path
-;session.save_path = "/var/lib/php5"
+session.save_path = "tcp://localhost:6379"

 ; Whether to use strict session mode.
 ; Strict session mode does not accept uninitialized session ID and regenerate

As you can see, it's simply a matter of changing session.save_handler from files to redis, and session.save_path to tcp://localhost:6379. Please note that you can actually use a Redis server running remotely by giving the remote machine's hostname here instead of localhost.

Once you've updated php.ini, you'll likely need to restart your web server, php-fpm, etc. After that's done, you can check that keys are being stored in the Redis server using redis-cli. The keys * command should return a list of keys that looks similar to this:

localhost:6379> keys *
    1) "PHPREDIS_SESSION:a1spmnakltr1213gl4gjh69710"
    2) "PHPREDIS_SESSION:kr6jksjntu6b7h29j43q5phi41"
    3) "PHPREDIS_SESSION:4222uts8503ma4jbv83dmds1i7"
    4) "PHPREDIS_SESSION:284gaa021ff38egj2ia4iv40g7"

And that's it! You've now got PHP sessions stored in Redis. You can go ahead and remove the keys that were previously being written to disk. (HINT: The value that was previously in session.save_path will tell you where those keys were stored on disk.)

Slaptijack's Koding Kraken