Connecting with PHP
This guide explains how to establish a connection between a PHP application and a Redis database using the phpredis extension. It walks through the necessary setup, configuration, and execution of a simple Redis command.
Variables
Certain parameters must be provided to establish a successful connection to a Redis database. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:
Variable |
Description |
Purpose |
---|---|---|
|
Redis hostname, from the Elestio service overview page |
The address of the server hosting your Redis instance. |
|
Port for Redis connection, from the Elestio service overview page |
The network port used to connect to Redis. The default port is 6379. |
|
Redis password, from the Elestio service overview page |
The authentication key required to connect securely to Redis. |
These values can usually be found in the Elestio service overview details as shown in the image below. Make sure to take a copy of these details and add it to the code moving ahead.
Prerequisites
- Install PHP
- Check if PHP is installed by running:
php -v
-
- If not installed, download it from php.net and install.
- Install the phpredis Extension
- The phpredis extension provides a native PHP interface for Redis. You can install it using:
sudo pecl install redis
-
- Then enable it in your php.ini:
extension=redis
-
- To verify it’s installed:
php -m | grep redis
Code
Once all prerequisites are set up, create a new file named redis.php
and add the following code:
<?php
$host = 'HOST';
$port = PORT;
$password = 'PASSWORD';
$redis = new Redis();
try {
$redis->connect($host, $port);
if (!$redis->auth($password)) {
throw new Exception('Authentication failed');
}
echo "Connected to Redis\n";
$redis->set("testKey", "Hello Redis");
$value = $redis->get("testKey");
echo "Retrieved value: $value\n";
$redis->close();
} catch (Exception $e) {
echo "Redis connection or operation failed: " . $e->getMessage() . "\n";
}
Open the terminal or command prompt and navigate to the directory where redis.php
is located. Once in the correct directory, run the script with the command:
php redis.php
If the connection is successful, the terminal will display output similar to:
Connected to Redis
Retrieved value: Hello Redis
No Comments