How to Use Redis in PHP

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you’re looking for a structured solution for storing data in memory, Redis may be the ideal choice. Redis is an open-source, in-memory data structure server, or key-value store. Its name is an abbreviated version of the phrase “Remote Dictionary Server”. What sets Redis apart from other key-value databases is its unique ability to handle high-level data types. Think hashes, sets, lists and more– implementing solutions involving these data structures with a relational database would be messy and inefficient. In this article, we’ll introduce you to some of the essential Redis data types and explain how to use Redis with PHP.

Prerequisites

Before we get into a deeper discussion of Redis and PHP, let’s review a couple of key prerequisites that must be in place to follow along with this tutorial:

  • First, you must ensure that Redis is installed and properly configured. To check for the Redis installation, use the redis-cli --version command. The output should look something like this:
1
redis-cli 4.0.9
  • You must also ensure that PHP is installed and configured with Redis. To check if you have PHP installed on your system, use the following command:
1
php -v

The output will look like the following:

1
2
3
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.6-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

What are Redis Datatypes?

As we mentioned earlier, Redis is a key-value store; thus, data in Redis is stored via a key-value method.

Shown below are some of the most common Redis data types:

  1. String — This data structure is similar to Strings in PHP.
  2. List — A list is a one-dimensional array in which we can push, pop, shift and unshift elements. These elements are placed in order of insertion: first in, first out.
  3. Hash— This data type acts as a map between string fields and string values. Hashes are the ideal data type to represent objects.
  4. Set — Sets are similar to lists; however, elements in a set may appear only once, and a set has no order.
  5. Sorted Set — This data structure is somewhat similar to a Redis set and has the same unique properties of values stored in sets. However, each member of a sorted set has a score associated with it, and members are ordered from the smallest score to the largest.

How to Connect PHP to a Redis Server

Let’s connect PHP to a Redis Server using the Redis Class:

1
$clientRedis = new Redis();

The code shown above uses the Redis class to connect to a Redis instance. This class allows us to access all the methods that we can take advantage of to use Redis with PHP.

We’ll also need to monitor various aspects of Redis’ performance, such as connections and overloading issues. To do this, we will be using the RedisException class:

1
2
3
4
5
6
7
8
9
function Redis_connect($hostname, $port){
try {

$connected = $clientRedis->connect($hostname, $port);
if (!$connected) { throw new Exception(); }
} catch (Exception $e) {
die($e->getMessage());
}
}

The function shown above connects to a Redis server while it monitors for possible issues during the process. To use this function in PHP, we simply call the function and provide the parameters for the $hostname and $port:

1
2
3
4
5
6
7
8
9
10
11
//Connecting to Redis server on localhost
Redis_connect("127.0.0.1", 6379);


echo "Connected to server successfully";
echo "
"
;
//check whether server is running or not
echo "Server is running: " . $redis->ping();
echo "
"
;

The output should look like the following:

1
2
Connection to server successful
Server is running: +PONG

What are Getters and Setters in Redis?

Now that we’ve provided an overview of the Redis data types and talked about how to connect to a Redis server, let’s take a look at the GET, SET and EXISTS commands. We’ll be making good use of these commands while working with Redis and PHP.

  • GET: This returns a value from a stored value at a particular key.
  • SET: This will store a string value; if a key already holds a value, this command will overwrite the existing value.
  • EXISTS: This simply checks if a given key exists or not.

In short, the above commands can be used to store, check, and get data from a Redis server. We can use the Redis class to perform our Redis operations using methods with the same name as the commands.

Let’s check out the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
// like the SET command this PHP script sets message to hold the "Hello world" string
$redis->set("message";, "Hello world");
echo "
"
;
// like the GET command this PHP script gets the value stored in the "key" message
$value = $redis->get("message");
echo "
"
;
// As expected this will print out Hello world
print($value);
echo "
"
;

echo ($redis->exists("message")) ? "Yes I hold a value" : "please store a value in the message key";

Your output will look something like the following:

1
2
Hello world
Yes I hold a value

Conclusion

It’s clear that Redis provides a simple and elegant way to store complex data structures in memory. You can use Redis with PHP to store and manipulate a wide variety of data structures including lists, sets, hashes and more. With the examples and instructions provided in this tutorial, you’ll be ready to write your own code using both Redis and PHP.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.