Skip to main content

Connecting with PHP

This guide explains how to establish a connection between a PHP application and a KeyDB database using the phpredis extension. It walks through the necessary setup, configuration, and execution of a simple KeyDB command.

Variables

Certain parameters must be provided to establish a successful connection to a KeyDB 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

HOST

KeyDB hostname, from the Elestio service overview page

The address of the server hosting your KeyDB instance.

PORT

Port for KeyDB connection, from the Elestio service overview page

The network port used to connect to KeyDB. The default port is 6379.

PASSWORD

KeyDB password, from the Elestio service overview page

The authentication key required to connect securely to KeyDB.

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.

Screenshot 2025-06-26 at 1.13.23 PM.jpg

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 KeyDB. 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 keydb.php and add the following code:

<?php

$host = 'HOST';
$port = PORT;
$password = 'PASSWORD';

$keydb = new Redis();

try {
    $keydb->connect($host, $port);

    if (!$keydb->auth($password)) {
        throw new Exception('Authentication failed');
    }

    echo "Connected to KeyDB\n";

    $keydb->set("testKey", "Hello KeyDB");
    $value = $keydb->get("testKey");
    echo "Retrieved value: $value\n";

    $keydb->close();

} catch (Exception $e) {
    echo "KeyDB connection or operation failed: " . $e->getMessage() . "\n";
}

Open the terminal or command prompt and navigate to the directory where keydb.php is located. Once in the correct directory, run the script with the command:

php keydb.php

If the connection is successful, the terminal will display output similar to: