Install Redis on Ubuntu And Simple PHP Script

Redis is an in-memory data structure store, used as a database server, cache, and message broker. Redis is written in C programming language. It also provides PHP module for communication between PHP script with the Redis server.
Installing Redis:
sudo apt-get install redis-server

Restart Redis service:
sudo apt-get install redis-server
Configure Redis:

sudo vim /etc/redis/redis.conf

Install Redis PHP Extension:
sudo apt-get install php-redis
Test Connection to Redis Server:
~$ redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379>
PHP Script:
<?php
  $redisObj = new Redis();
  $query = 'select * from employees limit 1'; 
  $arrValues = executeQuery( $query );
  $jsonValue = json_encode($arrValues);
  print_r($jsonValue);
  echo "<br /><br />"; 
  openRedisConnection( '127.0.0.1', 6379 );
  setValueWithTtl( 'somekey1', $jsonValue, 36000);
  $val = getValueFromKey( 'somekey1' ); 
  print_r($val);

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

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

   return $resultArray; 
  }

  function executeQuery( $query ){ 
     $mysqli = new mysqli( 'localhost',  'root',  'root',  'test' ); 
     if( $mysqli->connect_errno ){ 
       echo "Failed to connect to MySql:"."(".mysqli_connect_error().")".mysqli_connect_errno(); 
     } 
    $result =  $mysqli->query( $query );  
    $arrResult = convertToArray( $result ); 
   return $arrResult; 
   
  }

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

   try{ 
    global $redisObj; 
  // setting the value in redis
    $redisObj->setex( $key, $ttl, $value );
   }catch( Exception $e ){ 
    echo $e->getMessage(); 
   } 
  }
  function getValueFromKey( $key ){ 
   try{ 
    global $redisObj; 
  // getting the value from redis
    return $redisObj->get( $key);
   }catch( Exception $e ){ 
    echo $e->getMessage(); 
   } 
  }
?>

Comments