≡ Menu

How to Use Redis with PHP using PhpRedis with Examples

Redis is an open source, in-memory advanced key-value store. It is one of the fastest NoSQL database. Moreover, Redis cache store is a more advanced data-structure than memcached service.

For using Redis cache, we will have to pick a client. There are many PHP clients listed on its official website out of which phpredis is widely popular.

In this tutorial, we’ll use the API provided by “phpredis” extension to communicate with redis. This article covers the following:

  1. Configuring phpredis
  2. Using phpredis
  3. Frequently used PhpRedis Methods
  4. Example PHP Program using Redis

I. Configuring phpredis

First, download “phpredis” for github repository herehttps://github.com/nicolasff/phpredis

Once you’ve downloaded it, extract the files to phpredis directory. On ubuntu, install this extension as shown below.

cd phpredis

sudo phpize

sudo ./configure

sudo make

sudo make install

Now we have the phpredis extension installed. Copy and paste the content of “modules” folder to the php extension directory or use the following command in terminal.

sudo cp modules/redis.so {php-config–extension-dir}

Now, we need to configure php to use it. Add the following lines in php.ini for your php installation.

extension = redis.so

Or, we can also copy paste the redis.ini from ‘rpm’ folder to “php5/conf.d” folder to have a separate .ini file for redis.

Or, we can just create a redis.ini file there using following command:

sudo echo “extension=redis.so”  > /etc/php5/conf.d/redis.ini

II. Using phpredis

Phpredis extension imports the class Redis, which we can use to do various operations. The following are the classes which we can use:

1. Class Redis

This class is used to connect to redis instance. This class have all the methods which we need to interact with the redis.

We can create an instance of this following the syntax as follows:

$redisClient = new Redis();

2. Class RedisException

This class is used to monitor the issues like overloading and connection problems, as it throws an RedisException object to flag it. Internally this RedisException class in inherit the php “Exception” class.

You can use it following the sytax below:

  if( $socket = fsockopen( $host, $port, $errorNo, $errorStr )){
  	if( $errorNo ){
  	  throw new RedisException(“Socket cannot be opened”);
}catch( Exception $e ){
  echo $e -> getMessage( );

III. Frequently used PhpRedis Methods

1. Connect

This method is used to connect with the runnig redis instance.

We can use it following the sytax below:

$redisClient -> connect(“hostOrUnixPath”, “port”, “timeOut”, “reservedInterval” );

For Example:

  • $objRedis = new Redis();
  • $objRedis->connect( ‘localhost’, 6379 );
  • $objRedis->connect( ‘’ ); // By default it will take port 6379
  • $objRedis->connect( ‘’, 6379, 3.5 ); // Giving timeOut of 3.5 sec
  • $objRedis->connect( ‘/var/temp/redis/redis.sock’ ); // Unix domain socket path
  • $objRedis->connect( ‘’, 6379, 2.5, NULL, 150 ); // Delay of 150 ms in-between reconnection attempts with a time out of 2.5 sec

2. get

This is used to get the value associated with the specified key as shown below:

$redisClient -> get('key');

3. mget

To get the multiple value associated with the array of keys as shown below:

$arrKeys = array(“keyA”, “keyB”, “keyC”);
$redisClient -> mget($arrKeys);

4. set

This is used to set the key-value pair as shown below:

$redisClient -> set('key', 'value');

5. setex

This is used to set the key-value pair with time in seconds after which it should expire as shown below:

$redisClient -> setex('key', 3600, 'value' );

6. del

This is used to delete the key specified as shown below:

$redisClient -> del('key');

7. exists

This returns true if specified key exists else returns false as shown below:

$redisClient -> exists('key');

8. close

This is used to close the connection created as shown below:

$redisClient -> close();

IV. Example PHP Program using Redis

Generally redis is used as cache with some database server. We will see now, how we can use above methods to implement it as cache when stacked with PHP and MySql. Below is the working example of how to implement it.

  /* Functions for redis operations starts here   */ 

  $redisObj = new Redis(); 

  function openRedisConnection( $hostName, $port){ 
  	global $redisObj; 
	// Opening a redis connection
  	$redisObj->connect( $hostName, $port );
  	return $redisObj; 

  function setValueWithTtl( $key, $value, $ttl ){ 

  		global $redisObj; 
		// setting the value in redis
  		$redisObj->setex( $key, $ttl, $value );
  	}catch( Exception $e ){ 
  		echo $e->getMessage(); 

  function getValueFromKey( $key ){ 
  		global $redisObj; 
		// getting the value from redis
  		return $redisObj->get( $key);
  	}catch( Exception $e ){ 
  		echo $e->getMessage(); 

  function deleteValueFromKey( $key ){ 
  		global $redisObj; 
		// deleting the value from redis
  		$redisObj->del( $key);
  	}catch( Exception $e ){ 
  		echo $e->getMessage(); 

   /* Functions for converting sql result  object to array goes below  */ 

  function convertToArray( $result ){ 
  	$resultArray = array(); 

  	for( $count=0; $row = $result->fetch_assoc(); $count++ ) { 
  		$resultArray[$count] = $row; 

  	return $resultArray; 

   /* Functions for executing the mySql query goes below   */ 

  function executeQuery( $query ){ 
     $mysqli = new mysqli( 'localhost',  'username',  'password',  'someDatabase' ); 

     if( $mysqli->connect_errno ){ 
       echo "Failed to connect to MySql:"."(".mysqli_connect_error().")".mysqli_connect_errno(); 

     $result =  $mysqli->query( $query ); 
	 // Calling function to convert result  to array
     $arrResult = convertToArray( $result );

     return $arrResult;   	 

  $query = 'select * from sometable limit 1'; 
  // Calling function to execute sql query
  $arrValues = executeQuery( $query );

  // Making json string
  $jsonValue = json_encode($arrValues);

  // Opening a redis connection
  openRedisConnection( 'localhost', 6379 );

  // Inserting the value with ttl =  1 hours
  setValueWithTtl( 'somekey1', $jsonValue, 3600);

  // Fetching value from redis using the key. 
  $val = getValueFromKey( 'somekey1' ); 

  //  Output:  the json encoded array from redis 
  echo $val;

  // Unsetting value from redis
  deleteValueFromKey( $key );


In the above example PHP redis script, we are creating functions for various redis operations as explained in the comment inside the code. The script is well commented so that it is self explanatory. The flow of the script is as follows:

  1. In the above example, we execute a mysql query using the function executeQuery and then we are passing the value to function convertToArray() from where we will get the results as array.
  2. Next, we encode the array of results to json string and inserting it to redis.
  3. Finally, retrieve the string from the redis and display it.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • frank February 17, 2014, 8:31 pm

    Good job.
    Thank you so much.

  • Duane February 26, 2014, 9:12 pm

    The example works great. Thanks!

  • Jai Prakash July 15, 2014, 12:28 am

    Another way to install redis module is just to say on mac or linux distros by

    pecl install redis

  • ahad September 21, 2014, 9:43 pm

    Thanks for the great tutorial.
    Do you have any simple example to show how an existing php web page with mysql database connection can use node.js, socket.io, and redis for a realtime chat application?

  • Jason Statham January 7, 2015, 8:22 am

    $redisClient = new Redis();
    where I am create this instance how its working.
    Im didn’t get any idea..
    Pls explain this..

  • Bat March 27, 2015, 12:54 pm



    What you see here is an issue that was first discovered in 2011.
    Due to the authors inability to provide a robust session-id handler interface between Redis and PHP’s session handling this is still a serious problem in 2015.

    If you use this product on a high traffic website, you will inevitably encounter that users will “hijack” other users sessions. This is due to how phpredis generates non-PHP-conform session ids, randomly they contain character sequences that result in PHP returning an empty ID to the client. Let this happen to more than one user and they share a session. Let it be Friday 13th and a rogue user manages to accidentally “hijack” an admin account on your website and you can say goodbye.

  • veeru July 5, 2016, 4:44 am

    Hi Sir,

    Thanks for the great tutorial..Nice explanation…

  • Sabarish February 11, 2017, 5:50 am

    Can i have sample example of Hash set usage through PHP.