Using Redis for PHP Session Storage

by Scott Hebert

Redis logo -leftI 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.

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:

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