Sealos Logo

PHP

Learn how to connect to Redis databases in Sealos DevBox using PHP

This guide will walk you through the process of connecting to a Redis database using PHP within your Sealos DevBox project.

Prerequisites

Install Required Extensions

In your Cursor terminal, ensure that the Redis extension for PHP is installed:

sudo apt-get update
sudo apt-get install php-redis -y

Connection Setup

Create a Configuration File

First, let's create a configuration file to store our Redis connection parameters. Create a file named config.php in your project directory with the following content:

<?php
return [
    'host' => 'your_redis_host',
    'port' => 6379,
    'password' => 'your_redis_password'
];

Replace the placeholders with your actual Redis credentials from the Database app in Sealos.

Create a Redis Connection Function

Next, let's create a PHP file that will handle the Redis connection. Create a file named redis_connect.php with the following content:

<?php
function getRedisConnection() {
    $config = include 'config.php';
    
    try {
        $redis = new Redis();
        $redis->connect($config['host'], $config['port']);
        
        if (isset($config['password']) && !empty($config['password'])) {
            $redis->auth($config['password']);
        }
        
        echo "Connected successfully to Redis.\n";
        return $redis;
    } catch (Exception $e) {
        die("Connection failed: " . $e->getMessage());
    }
}

This function reads the configuration from config.php and establishes a connection to the Redis database.

Create a Test Script

Now, let's create a test script to verify our connection and perform some basic Redis operations. Create a file named test_redis.php with the following content:

<?php
require_once 'redis_connect.php';
 
$redis = getRedisConnection();
 
// Set a key
$redis->set('mykey', 'Hello from Sealos DevBox!');
echo "Key set successfully.\n";
 
// Get a key
$value = $redis->get('mykey');
echo "Retrieved value: " . $value . "\n";
 
// Set a hash
$redis->hSet('myhash', 'field1', 'value1');
$redis->hSet('myhash', 'field2', 'value2');
echo "Hash set successfully.\n";
 
// Get hash fields
$hashValue = $redis->hGetAll('myhash');
echo "Retrieved hash: " . print_r($hashValue, true) . "\n";
 
// Close the connection
$redis->close();
echo "Redis connection closed.\n";

This script demonstrates setting and getting a key, as well as working with Redis hashes.

Usage

To run the test script, use the following command in your Cursor terminal:

php test_redis.php

This will execute the script, demonstrating the connection to Redis and basic operations.

Best Practices

  1. Use environment variables or a separate configuration file for Redis credentials.
  2. Handle potential errors using try-catch blocks.
  3. Close the Redis connection after operations are complete.
  4. Use Redis transactions for operations that need to be atomic.
  5. Consider using a connection pool for better performance in production environments.

Troubleshooting

If you encounter connection issues:

  1. Verify your Redis credentials in the config.php file.
  2. Ensure your Redis database is running and accessible.
  3. Check for any network restrictions in your DevBox environment.
  4. Confirm that the php-redis extension is correctly installed.

For more detailed information on using Redis with PHP, refer to the official PHP Redis documentation.

Edit on GitHub

Last updated on

On this page