Complete Guide to Redis PHP

Redis, an acronym for “Remote DIctionary Server,” is an open-source, in-memory data structure store that can be used as a caching mechanism, message broker, and data store. In this article, we will delve into Redis integration with PHP, covering its installation, how to connect to a Redis server, common Redis commands, and practical examples.

Important Topics for Redis PHP

  • Installing the Redis Server in PHP
  • Installing PHP Redis Extension
  • Configure Redis
  • Redis Data Types and Commands in PHP
  • Close the Connection
  • Conclusion

Installing the Redis Server in PHP

To interact with Redis in PHP, you’ll need the Redis extension. You can install it using the following command:

pecl install redis

Installing PHP Redis Extension

Once the extension is installed, you can enable it by adding the following line to your php.ini file:

extension=redis.so

Note: After enabling the extension, restart your web server to apply the changes.

Now, you can establish a connection to your Redis server using PHP:

PHP




<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379); // Replace with your Redis server's IP and port
?>


Configure Redis

Redis configuration usually doesn’t require extensive changes for basic usage. However, you can fine-tune Redis by editing the redis.conf file. Common configurations include setting the maximum memory usage, changing the default port, and enabling authentication. Remember to restart the Redis service after making any configuration changes.

Redis Data Types and Commands in PHP

Redis supports various data types and provides a wide range of commands to manipulate them. Here are the Redis data types and commands:

Strings are simple key-value pairs in Redis. You can set, get, and manipulate strings using commands like:

  • SET
  • GET
  • INCR, and
  • DECR.

Example: We will set a new organisation name as Beginner for Beginner in our Redis PHP Database.

$redis->set(‘org’, ‘Beginner for Beginner’);echo $redis->get(‘org’); // Outputs: “Beginner for Beginner”

Lists

Lists in Redis are ordered collections of strings. You can use commands like:

  • LPUSH
  • RPUSH
  • LPOP, and
  • RPOP to add and remove items from a list.

PHP




$redis->lpush('courses', 'dsa');
$redis->lpush('courses', 'sys_design');
$redis->rpush('courses', 'android');
 
$fruits = $redis->lrange('courses', 0, -1);
print_r($courses);
// Outputs: ["sys_design", "dsa", "android"]


Sets in Redis are unordered collections of unique strings. You can use commands like:

  • SADD
  • SMEMBERS, and
  • SREM to manipulate sets.

Example: In our Beginner for Beginner DB, we are now adding the prices of the courses:

PHP




$redis->sadd('prices', '400');
$redis->sadd('prices', '300');
$redis->sadd('prices', '200');
 
$colors = $redis->smembers('prices');
print_r($prices); // Outputs: ["400", "300", "200"]


Hashes in Redis are maps between string fields and string values. You can use commands like:

  • HSET
  • HGET, and
  • HDEL to work with hashes.

Example: We will be adding a new user to the first course, named Spandan whose age is 22

PHP




$redis->hset('user:1', 'name', 'Spandan');
$redis->hset('user:1', 'age', 22);
$user = $redis->hgetall('user:1');
print_r($user); // Outputs: ["name" => "Spandan", "age" => "22"]


Sorted Sets in Redis are similar to sets but with a score associated with each member. You can use commands like:

  • ZADD
  • ZRANGE,
  • and ZREM to work with sorted sets.

Example: In the following example, we will be organizing and sorting the Redis data based on the score in their GfG assessment.

PHP




$redis->zadd('scores', 100, 'Spandan');
$redis->zadd('scores', 85, 'Ankur');
$redis->zadd('scores', 95, 'Anuj');
$topScorers = $redis->zrange('scores', 0, -1);
print_r($topScorers); // Outputs: ["Ankur", "Anuj", "Spandan"]


Key Expiry

You can set an expiration time for keys in Redis using the:

  • EXPIRE and
  • TTL command

Example: We will now be searching for the keys, if they exist, the user will be prompted.

PHP




$redis->set('key', 'value');
$redis->expire('key', 40); // Key expires in 40 seconds
// Check the time left for key expiration
$timeLeft = $redis->ttl('key');
echo "Time left: $timeLeft seconds";


Redis PHP Keys

Redis provides commands to manipulate keys, including:

  • DEL
  • EXISTS, and 
  • KEYS. 

Here’s an example of checking if a key exists and deleting it:

PHP




$redis->set('key1', 'dsa');
if ($redis->exists('key1')) {
    echo "DSA 'key1' exists!\n";
    $redis->del('key1');


Caching with Redis

One of the most common use cases for Redis in PHP is caching. You can store the results of expensive database queries or API requests in Redis to speed up your application.

PHP




$key = 'user:121';
if ($redis->exists($key)) {
    $userData = unserialize($redis->get($key));
} else {
    $userData = fetchUserDataFromDatabase(121);
    $redis->setex($key, 4600, serialize($userData)); // Cache for more than an hour
}


Close the Connection

When you’re finished with your Redis operations, it’s essential to close the connection to release resources:

PHP




$redis->close();


Conclusion:

Redis is a powerful and versatile tool that can significantly enhance the performance and functionality of your PHP applications. In this article, we’ve covered the basics of installing Redis, connecting to it from PHP, common data types, and essential commands, and provided practical examples of how Redis can be used in real-world scenarios. By integrating Redis into your PHP projects, you can unlock new possibilities for speed, scalability, and real-time capabilities in your applications.



Contact Us