Connecting with PHP
This guide explains how to establish a connection between a PHP application and a Valkey database using the phpredis extension. It walks through the necessary setup, configuration, and execution of a simple Valkey command.
Variables
Certain parameters must be provided to establish a successful connection to a Valkey 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 |
---|---|---|
|
Valkey hostname, from the Elestio service overview page |
The address of the server hosting your Valkey instance. |
|
Port for Valkey connection, from the Elestio service overview page |
The network port used to connect to Valkey. The default port is 6379. |
|
Valkey password, from the Elestio service overview page |
The authentication key required to connect securely to Valkey. |
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 Valkey. 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 valkey.php
and add the following code:
<?php
$host = 'HOST';
$port = PORT;
$password = 'PASSWORD';
$valkey = new Redis();
try {
$valkey->connect($host, $port);
if (!$valkey->auth($password)) {
throw new Exception('Authentication failed');
}
echo "Connected to Valkey\n";
$valkey->set("testKey", "Hello Valkey");
$value = $valkey->get("testKey");
echo "Retrieved value: $value\n";
$valkey->close();
} catch (Exception $e) {
echo "Valkey connection or operation failed: " . $e->getMessage() . "\n";
}
Open the terminal or command prompt and navigate to the directory where valkey.php
is located. Once in the correct directory, run the script with the command:
php valkey.php
If the connection is successful, the terminal will display output similar to: