Using Redis as a session handler in Php

Redis Introduction

Redis is an open source, in-memory data structure store, used as a database and cache.
Redis is a persistent key-value database with built-in net interface written in ANSI-C for Posix systems.
In order to achieve its outstanding performance, Redis works with an in-memory dataset.

Redis is an open source key value data structure store. keys can be strings, hashes, lists, sets, sorted sets etc.
This in memory data store is broadly used in session state storing and caching.

Depending on your use case, you can persist it either by dumping the dataset to disk every once in a while, or
by appending each command to a log.
Persistence can be optionally disabled, if you just need a feature-rich, networked, in-memory cache.

The Redis documentation is a good way to start learning how Redis works as well as how to configure it for your specific application.

Why Redis as session handler

The session handler is responsible for storing and retrieving data saved into sessions – by default, PHP uses files for that. we can use the database to store and retrieve the session.
An external session handler can be used for creating large scalable PHP environments behind a load balancer, where all application nodes will connect to a central server to share session information.

Here, i will explain how redis server can be used as a session handler for a PHP application running on Ubuntu 14.x.

But before that, we need to configure redis on our server.
Read Install and Configure Redis server on Ubuntu 14.x

configuring session Handler

After success in configuration (well tested client and server running), we need to make few changes in the server configuration file ie. php.ini
1) session.save_handler
By deffault php comes with the session handler to files, we need to make it redis
session.save_handler= redis
2) uncomment the session.save_path
session.save_path = tcp://

3) Now make an simple program in php that uses the session.

<?php //simple counter to test sessions. should increment on each page reload. 
$count = isset($_SESSION['count']) ? $_SESSION['count'] : 1;
 echo $count;
 $_SESSION['count'] = ++$count;

when you run the file again and again (reload), then the $count will increment every time , as per the program

Till Now, it shows that session in created and storing the values $count in session
But to really know, thats its redis session,
Go to your terminal in ubuntu and type redis-cli -h Ipaddress
ex. redis-cli -h> keys *
1) “PHPREDIS_SESSION:o1phk2jkc4hmgp36bkqf0v9bj5”
Redis cli





this shows that the redis session key is generated.
Sit Back and Enjoy as redis session is working in php.