How to Use Vultr Managed Databases for Redis in PHP

Updated on October 16, 2023
How to Use Vultr Managed Databases for Redis in PHP header image

Introduction

A Vultr Managed Database for Redis is a highly available in-memory data store with flexible data structures such as strings, hashes, lists, and sets. You can use a Redis database with PHP to build highly available applications with fast response rates as compared to disk-based databases.

This guide explains how to use a Vultr Managed Database for Redis with PHP to interact with different data types in your web application.

Prerequisites

Before you begin:

Prepare the Development Server

PHP is a server-side object-oriented programming language. To run PHP files, prepare the development server with the necessary packages and configurations. To integrate with a Vultr Managed Database for Redis, install the php-redis extension and set up the web server configurations to read PHP files on the server.

  1. Verify the installed PHP version on your server

     $ php -v

    Your output should look like the one below:

     PHP 8.1.2-1ubuntu2.14 (cli) (built: Aug 18 2023 11:41:11) (NTS)
     Copyright (c) The PHP Group
     Zend Engine v4.1.2, Copyright (c) Zend Technologies
         with Zend OPcache v8.1.2-1ubuntu2.14, Copyright (c), by Zend Technologies
  2. Install the php-redis extension on your server

     $ sudo apt install php-redis
  3. Enable the Apache PHP module on your server depending on your PHP version

     $ sudo a2enmod php8.1
  4. Restart the Apache web server to save changes

     $ sudo systemctl restart apache2
  5. Navigate to the Apache virtual host files directory

     $ cd /etc/apache2/sites-enabled
  6. View your virtual host configuration file. By default, 000-default.conf

     $ cat 000-default.conf
  7. Keep note of the configured DocumentRoot value. Usually, /var/www/html

     ServerAdmin webmaster@localhost
     DocumentRoot /var/www/html
  8. Allow the HTTP port 80 through your server firewall to access your PHP files

     $ sudo ufw allow 80/tcp
  9. Using a text editor such as Nano, create a new info.php file in your web root directory

     $ nano /var/www/html/info.php
  10. Add the following contents to the file to test your PHP and Redis module configuration

    <?php
    
    if (extension_loaded('redis')) {
        echo 'The PHP Redis extension is installed on your server';
    } 
    else 
    {
        echo 'The PHP Redis extension is not installed. Please Install it and Restart Apache';
    }
    
    ?>

    Save and close the file

  11. Visit your server IP address and load the info.php file

    http://SERVER-IP/info.php

    Verify that a PHP Redis installed prompt displays on the web page

You have prepared your development server to read and serve PHP scripts. Integrate your Vultr Managed Database for Redis to enhance your PHP application functions and sync with the database.

Create a Redis PHP Database Class

To organize your PHP code, create a Redis PHP database class to declare your database information. Within your PHP applications, you can import the class to use your Redis database connection. Create a new connection class as described in the steps below.

  1. Navigate to your web root directory to store PHP files

     $ cd /var/www/html/
  2. Create a new RedisGateway.php file

     $ sudo nano RedisGateway.php
  3. Add the following contents to the file. Replace the example values with your actual Vultr Managed Database for Redis details in the $host, $port, $user, and $pass variables.

     <?php
    
     ini_set('display_errors', 1);
     ini_set('display_startup_errors', 1);
     error_reporting(E_ALL);
    
      class RedisGateway {
    
          public $redis_client;
    
          public function __construct()
          {
    
             $host = 'vultr-prod-example.vultrdb.com';
             $port = 16752;
             $user = "default";
             $pass = "example-password";   
    
             $redis = new Redis();
             $redis->connect("tls://" . $host, $port);
             $redis->auth([$user, $pass]);
    
             $this->redis_client = $redis;
          }
      }

    Save and close the file.

    Below is what the above PHP application methods and functions do:

    • __construct(): Initializes a connection to the Redis server when you create an instance of the RedisGateway class using the PHP new keyword
    • $redis = new Redis();: imports the Redis PHP driver
    • $redis->connect("tls://" . $host, $port);: Connects to the Vultr Managed Database for Redis
    • $redis->auth([$user, $pass]);: Defines the Redis database connection details
    • $this->redis_client = $redis;: Populates the $redis_client public property with the Redis database connection details
  4. To import the above PHP class, use the following declarations in your application

     require_once('RedisGateway.php');
    
     $redis_gateway = new RedisGateway();
     $redis_client  = $redis_gateway->redis_client;

Use Redis Strings in PHP

A string is a collection of bytes. You can use the Redis string data type to store text, binary arrays, and serialized objects. When using Redis as a cache, you can use the string data type to store values such as login tokens, user profile information, and frequently visited HTML pages. Implement Redis Strings in your application as described below

  1. Create a new redis_strings.php file

     $ sudo nano redis_strings.php
  2. Add the following contents to the file

     <?php
    
         require_once('RedisGateway.php');
    
         $redis_gateway = new RedisGateway();
         $redis_client  = $redis_gateway->redis_client;
    
         $redis_key =  "john_doe";
         $key_value = "example-password";
    
         $redis_client->set($redis_key, $key_value); 
    
         $redis_client->expire($redis_key, 3600); 
    
         $redis_value = $redis_client->get($redis_key); 
    
         echo $redis_value ;

    Save and close the file.

    Below is what the above PHP application functions do:

    • require_once('RedisGateway.php');: Imports the custom RedisGateway class to use the Redis connection information
    • $redis_client->set($redis_key, $key_value);: Sets a new key in the Redis database
    • $redis_key: Creates a new Redis key with the value john_doe
    • $key_value: Sets the Redis key value to example-password
    • $redis_client->expire($redis_key, 3600);: Sets the Redis key expiration time in seconds. 3600 sets the expiration time to 1 hour
    • $redis_client->get($redis_key);: Retrieves the Redis key value from the database
    • echo $redis_value: Prints the Redis key value from the database
  3. Using the curl utility, run the PHP application using your localhost IP Address

     $ curl http://127.0.0.1/redis_strings.php

    Output:

      example-password

    As displayed in the above output, the PHP application prints the Redis key-value example-password from the database.

Implement Redis Hashes

A hash is a collection of field-value pairs. Unlike strings, a Redis hash allows you to store multiple field values under one key. For instance, you can use a hash to save user session data in a Redis database in a single key. Implement Redis hashes in your PHP application as described below

  1. Create a new redis_hashes.php file

     $ sudo nano redis_hashes.php
  2. Add the following contents to the file

     <?php
    
         require_once('RedisGateway.php');
    
         $redis_gateway = new RedisGateway();
         $redis_client  = $redis_gateway->redis_client; 
    
         $redis_hash_key =  "users";
    
         $username = "john_doe";
         $password = "example-strong-password";
    
         $redis_client->hset($redis_hash_key, $username, $password);
    
         echo $redis_client->hget($redis_hash_key, $username);

    Save and close the file.

    In the above application code:

    • $redis_hash_key: Defines the Redis hash key
    • $username: Defines the key for each element in the Redis hash
    • $password: Stores the value for each element in the key
    • $redis_client->hset($redis_hash_key, $username, $password);: Creates and populates the Redis hash with data
    • echo $redis_client->hget($redis_hash_key, $username);: Retrieves the value of a given key from the hash
  3. Run the redis_hashes.php application file

     $ curl http://127.0.0.1/redis_hashes.php

    Output:

      example-strong-password

Implement Redis Sorted Sets

A sorted set is a collection of unique Redis strings ordered by an associated score. For example, in a fitness PHP application, you can use the Redis set data type to store and analyze walking distances for the application users. Implement Redis sorted sets as described in the following PHP application.

  1. Create a new redis_sorted_sets.php file

     $ sudo nano redis_sorted_sets.php
  2. Add the following contents to the file

     <?php
    
         require_once('RedisGateway.php');
    
         $redis_gateway = new RedisGateway();
         $redis_client  = $redis_gateway->redis_client; 
    
         $redis_set_key = 'steps_per_day';
    
         $redis_client->zadd($redis_set_key, 1910, 'JOHN'); 
         $redis_client->zadd($redis_set_key, 2180, 'JAMES');  
         $redis_client->zadd($redis_set_key, 5780, 'PETER');   
    
         print_r($redis_client->zrange($redis_set_key, 0, 2, true));  

    Save and close the file.

    In the above application:

    • $redis_set_key: Defines the name of the sorted Redis set
    • $redis_client->zadd(...);: Adds a string and the associated score to the Redis database
    • $redis_client->zrange($redis_set_key, 0, 2, true): Retrieves the sorted sets values from the Redis database
  3. Run the redis_sorted_sets.php application file

     $ curl http://127.0.0.1/redis_sorted_sets.php

    Output:

     Array
     (
         [JOHN] => 1910
         [JAMES] => 2180
         [PETER] => 5780
     )

Implement Redis Lists

In Redis, a list is an ordered sequence of strings for implementing stacks and queue-based applications. Redis allows you to add values to the left or right side of a list using the lpush and rpush directives. lPop and rPop retrieve and remove elements from a list respectively. Implement Redis lists as described in the following example PHP application

  1. Create a new redis_lists.php file

     $ sudo nano redis_lists.php
  2. Add the following contents to the file

     <?php
    
         require_once('RedisGateway.php');
    
         $redis_gateway = new RedisGateway();
         $redis_client  = $redis_gateway->redis_client; 
    
         $list_key = "countries";         
    
         $redis_client->lpush($list_key, "India");
         $redis_client->lpush($list_key, "Brazil");
         $redis_client->rpush($list_key, "France");
    
         $keys = $redis_client->lrange($list_key, 0, 2);
    
         print_r($keys);
    
         $i = 0;
    
         while ($redis_client->llen($list_key) > 0) {    
    
             print_r($redis_client->lPop($list_key));
    
             $i++;
    
         }

    Save and close the file.

    In the above PHP application:

    • $list_key: Declares the Redis key name
    • $redis_client->lrange($list_key, 0, 2);: Retrieves all the list values from the Redis server
    • $redis_client->llen($list_key): Finds the length of a list or the total elements in the list
    • while ($redis_client->llen($list_key) > 0) {...}: loops through the Redis list and runs the lPop('test_list') function to display and remove elements from the list
  3. Run the redis_lists.php application file

     $ curl http://127.0.0.1/redis_lists.php

    Output:

     Array
     (
         [0] => India
         [1] => Brazil
         [2] => France
     )

Conclusion

In this article, you have integrated a Vultr Managed Database for Redis with PHP and implemented several data types to work with the stored database values. By implementing Redis in your PHP application, you can speed up your application processes as compared to relational databases.

Next Steps

To integrate more applications and implement more data types using your Vultr Managed Database for Redis, visit the following resources.