Redis as a PHP Session Handler

Redis is one of my favorite key-value stores, the range of data types alone make it a must have in any developer”s tool belt. Another great use for Redis is as your session handler in PHP. The optional persistence that Redis provides makes it a better option than using Memcached for your sessions and the fact that it is in-memory means that it will be just as fast.

For this example you will need to be using phpredis which has to be compiled from source. You could use a PHP Client like Rediska or Predis but you would need to write a custom session handler to do so. Using the compiled extension allows you to use Redis for your session handler in a couple of lines. Before moving forward with these examples you will want to install the PHP Redis Extension.

Much like using Memcached for sessions, using Redis for your sessions can be accomplished with a few lines. If so desired you can make an change in php.ini to use Redis for all of your sites:

session.save_handler = redis
session.save_path    = tcp://

or directly in your page:

ini_set('session.save_handler', 'redis'
ini_set('session.save_path',    'tcp://'

In addition to the host and post there are some additional options which can be added in query string format. Unlike Memcached, you won’t need to encode the ampersands. First off, we have persistent which can be set to 0 (default) or 1 to disable or enable persistent connections. It’s still considered experimental at the time of this writing. Not quite experimental but equally as sketchy is database which defaults to 0 but could be set to any database number that is available on your system. I say it’s sketchy because at this time even if you set it, it doesn’t respect what database you select (there’s a bug on the project for it).

We also have weight when multiple servers are in play (just comma separate the hosts when setting the save_path) and timeout which is self explanatory. If you happen to be using authentication on your Redis instance, you can set it with auth. Last but not least is the prefix option (default “PHPREDIS_SESSION:”). Somewhat counterintuitive, phpredis does not respect the session name set in php.ini or with session_name(). To set the profile you will need to pass it as part of the session.save_path.

Remember, to get the power of persistence with your sessions, you will need to make sure that Redis is properly configured to be persistent in your redis.conf. Continuing with the topic of alternative session handlers, tomorrow I will be discussing using SQLite to store your sessions!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.