Redis – Installation and basic usage

redisRedis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. This article shows how to install Redis to work with Linux-based PHP development environment.

Installation and Configuration

  1. Download and install Redis
    [root@signals phpredis-master]# wget
    [root@signals phpredis-master]# tar xzf redis-2.6.11.tar.gz
    [root@signals phpredis-master]# cd redis-2.6.11
    [root@signals phpredis-master]# make
  2. To have redis run as a daemon, edit redis.conf, change:
    daemonize yes
  3. Start redis:
    [root@signals phpredis-master]# src/redis-server &
  4. OR: create a init script for redis
    • Create a new file  /etc/init.d/redis-server with the following content
      # redis - this script starts and stops the redis-server daemon
      # chkconfig:   - 85 15 
      # description:  Redis is a persistent key-value database
      # processname: redis-server
      # config:      /etc/redis/redis.conf
      # config:      /etc/sysconfig/redis
      # pidfile:     /var/run/
      # Source function library.
      . /etc/rc.d/init.d/functions
      # Source networking configuration.
      . /etc/sysconfig/network
      # Check that networking is up.
      [ "$NETWORKING" = "no" ] && exit 0
      prog=$(basename $redis)
      [ -f /etc/sysconfig/redis ] && . /etc/sysconfig/redis
      start() {
          [ -x $redis ] || exit 5
          [ -f $REDIS_CONF_FILE ] || exit 6
          echo -n $"Starting $prog: "
          daemon $redis $REDIS_CONF_FILE
          [ $retval -eq 0 ] && touch $lockfile
          return $retval
      stop() {
          echo -n $"Stopping $prog: "
          killproc $prog -QUIT
          [ $retval -eq 0 ] && rm -f $lockfile
          return $retval
      restart() {
      reload() {
          echo -n $"Reloading $prog: "
          killproc $redis -HUP
      force_reload() {
      rh_status() {
          status $prog
      rh_status_q() {
          rh_status >/dev/null 2>&1
      case "$1" in
              rh_status_q && exit 0
              rh_status_q || exit 0
              rh_status_q || exit 7
              rh_status_q || exit 0
              echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
              exit 2
    • Set permission to execute it:
      [tienlv@localhost src]$ chmod +x /etc/init.d/redis-server
    • Enable redis-server at startup:
      chkconfig redis-server on
    • Start/stop/restart the redis with
      /etc/init.d/redis-server stop|start|restart
  5. Install Redis php
    [root@signals phpredis-master]# wget
    [root@signals phpredis-master]# mv master
    [root@signals phpredis-master]# unzip
    [root@signals phpredis-master]# cd phpredis-master
    [root@signals phpredis-master]# phpize
    [root@signals phpredis-master]# ./configure
    [root@signals phpredis-master]# make && make install
  6. If you still do not see redis with phpinfo(), check where is the conf.d of php, and then add a new file: redis.ini with the following content
    ;configure the redis module
  7. To check if php redis is installed properly, create a new php file containing the following line:
        $redis = new Redis();
        $redis->connect('', 6379);//default port

Basic Usage


The most important commands used with Redis are SETGET, and EXISTS. You can use these commands to store and check on temporary information that is going to be accessed multiple times, typically in a key/value manner. For example:

$redis->set("hello_world", "Hi from php!");
$value = $redis->get("hello_world");

echo ($redis->exists("Santa Claus")) ? "true" : "false";

The set() method is used to set a value to a particular key, in this case the key is “hello_world” and the value is “Hi from php!” The get() method retrieves the value for the key, again in this case “hello_world”. The exists() method reports back whether the provided key is found or not in Redis’ storage.

The key is not restricted to alphanumeric characters and the underscore. The following will work just as well:

$redis->set("I 2 love Php!", "Also Redis now!");
$value = $redis->get("I 2 love Php!");


The INCR and DECR commands are used to increment and decrement values and are a great way to maintain counters. INCR and DECR increment/decrement their values by 1; you can also use INCRBY and DECRBY to adjust by larger intervals. Here’s an example:

// increment the number of views by 1 for an article
// with id 234

// increment views for article 237 by 5
$redis->incrby("article_views_237", 5);

// decrement views for article 237

// decrement views for article 237 by 3
$redis->decrby("article_views_237", 3);

Redis Data Types

As I mentioned earlier, Redis has built-in data types. You may be thinking that it’s odd to have data types in a NoSQL key-value storage system such as Redis, but this would be useful for developers to structure the information in a more meaningful way and perform specific operations which is typically much faster when the data is typed. Redis’ data types are:

  • String – the basic data type used in Redis in which you can store from few characters to the content of an entire file.
  • List – a simple list of strings order by the insertion of its elements. You can add and remove elements from both the list’s head and tail, so you can use this data type to implement queues.
  • Hash – a map of string keys and string values. In this way you can represent objects (think of it as a one-level deep JSON object).
  • Set – an unordered collection of strings where you can add, remove, and test for existence of members. The one constraint is that you are not allowed to have repeated members.
  • Sorted set – a particular case of the set data type. The difference is that every member has and associated score that is used order the set from the smallest to the greatest score.

So far I’ve only demonstrated strings, but there are commands that make working with data in other data types just as easy.


These commands are used to work with Redis’ hash data type:

  • HSET – sets the value for a key on the the hash object.
  • HGET – gets the value for a key on the hash object.
  • HINCRBY – increment the value for a key of the hash object with a specified value.
  • HDEL – remove a key from the object.
  • HGETALL – get all keys and data for a object.

Here’s an example that demonstrates their usage:

$redis->hset("taxi_car", "brand", "Toyota");
$redis->hset("taxi_car", "model", "Yaris");
$redis->hset("taxi_car", "license number", "RO-01-PHP");
$redis->hset("taxi_car", "year of fabrication", 2010);
$redis->hset("taxi_car", "nr_starts", 0);
$redis->hmset("taxi_car", array(
    "brand" => "Toyota",
    "model" => "Yaris",
    "license number" => "RO-01-PHP",
    "year of fabrication" => 2010,
    "nr_stats" => 0)
echo "License number: " . 
    $redis->hget("taxi_car", "license number") . "<br>";

// remove license number
$redis->hdel("taxi_car", "license number");

// increment number of starts
$redis->hincrby("taxi_car", "nr_starts", 1);

$taxi_car = $redis->hgetall("taxi_car");
echo "All info about taxi car";
echo "<pre>";
echo "</pre>";


These are the important commands for working with the list type in Redis. A Redis list is similar to an array in PHP, and offer a great support for implementing queues, stacks, or a capped collection of a certain number of elements.

  • LPUSH – prepends element(s) to a list.
  • RPUSH – appends element(s) to a list.
  • LPOP – removes and retrieves the first element of a list.
  • RPOP – removes and retrieves the last element of a list.
  • LLEN – gets the length of a list.
  • LRANGE – gets elements from a list.
$list = "PHP Frameworks List";
$redis->rpush($list, "Symfony 2");
$redis->rpush($list, "Symfony 1.4");
$redis->lpush($list, "Zend Framework");

echo "Number of frameworks in list: " . $redis->llen($list) . "<br>";

$arList = $redis->lrange($list, 0, -1);
echo "<pre>";
echo "</pre>";

// the last entry in the list
echo $redis->rpop($list) . "<br>";

// the first entry in the list
echo $redis->lpop($list) . "<br>";


Most likely, when you set a key you don’t want it to be saved forever because after a certain period of time it’s not likely to be relevant anymore. You’ll need to update its value or delete it to reduce memory usage for better performance. Redis offers four commands that let you handle data persistence easily.

  • EXPIRE – sets an expiration timeout (in seconds) for a key after which it and its value will be deleted.
  • EXPIREAT – sets and expiration time using a unix timestamp that represents when the key and value will be deleted.
  • TTL – gets the remaining time left to live for a key with an expiration.
  • PERSIST – removes the expiration on the given key.
// set the expiration for next week
$redis->set("expire in 1 week", "I have data for a week");
$redis->expireat("expire in 1 week", strtotime("+1 week"));
$ttl = $redis->ttl("expire in 1 week"); // will be 604800 seconds

// set the expiration for one hour
$redis->set("expire in 1 hour", "I have data for an hour");
$redis->expire("expire in 1 hour", 3600);
$ttl = $redis->ttl("expire in 1 hour"); // will be 3600 seconds

// never expires
$redis->set("never expire", "I want to leave forever!");

Use phpRedisAdmin to manage redis servers

  1. Get it: 
    unzip master
    rm -fr master
    mv phpRedisAdmin-master phpRedisAdmin
    cd phpRedisAdmin
  2. Edit its config in include/config.php file.
  3. Get predis lib for its operations:
    cd predis/
    unzip v0.8
    rm -fr v0.8
    mv predis-0.8/* ./
    mv predis-0.8/.travis.yml ./
    mv predis-0.8/.gitignore ./
    rm -fr predis-0.8
  4. For secure access:
    1. Create .htpasswd file  (use to generate password, or use htpasswd tool)
    2. Create .htaccess file:
      AuthUserFile /full/path/to/.htpasswd
      AuthType Basic
      AuthName "My Redis Admin server"
      Require valid-user


Indeed Redis has much more to offer than just being a Memcache replacement.

Redis is here for the long run; it has a growing community, support for all major languages, and offers durability and high-availability with master-slave replication. Redit is open source, so if you’re a C guru then you can fork its source code from GitHub and become a contributor.

If you’re looking for more information beyond the project site, you might want to consider checking out two great Redis books, Redis Cookbook and Redis: The Definitive Guide.

About NhocConan

A super lazy guy who tries to write tech blog entries in English.He is lazy, so he can only write when he is in a good mood or when he is tired of coding.

Leave a comment

Your email address will not be published. Required fields are marked *