Redis Sessions in PHP with Kohana

Writing software that scales with little effort can be a daunting task. The days of "throw hardware at the problem" are here, and managing a web farm with dozens of servers is a real problem for PHP developers. When moving from one to many web servers, the first task is managing PHP session consistency. We will discuss how to accomplish this using the Redis PHP Session Save Handler.

Install

First, you will need to build Redis from source and then build the PHP-Redis extension from source. You can skip this step if you are using our Vagrant development environment!

Configure

Now you will need to enable the Redis PHP session handler in your php.ini

[PHP]
extension=redis.so
 
[Session]
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

View Stats

You may want to see the current status of your Redis installation. Often times you will find yourself wondering how many cache keys exist with a particular prefix. A working COUNT function was rejected by the Redis core developers; however, Redis 2.6.0 supports the EVAL function via a Lua interpreter. Now you can get the count of any Redis key by prefix:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$count = $redis->eval('return table.getn(redis.call("keys", "PHPREDIS_SESSION:*"))');

Below is the output from our Redis dashboard in Zen Kommerce. You can see that we are keeping counts of session and specific cache keys by prefix.

Redis Dashboard

Summary

With Redis you now have a fully-functional data structure server that will help you scale your web applications. I have seen and managed multi-server production installations using PHP session save handlers with the standard file handler coupled with NFS, Memcache, and even a MySQL Database. So far Redis has been the tool of choice.


All rights reserved