Skip to main content

Connect with PHP

Connect to the Aiven for Valkey™ database using PHP, making use of the predis library.

Variables

Replace placeholders in the code sample with values from your service overview page:

VariableDescription
SERVICE_URIURI for the Aiven for Valkey service connection

Prerequisites

Install the predis library using the following command:

composer require predis/predis

Set up and run

  1. Create a file named index.php and insert the code below, substituting the placeholder with your Aiven for Valkey URI:

    <?php

    require 'vendor/autoload.php';
    Predis\Autoloader::register();

    $service_uri = 'SERVICE_URI';

    $client = new Predis\Client($service_uri);

    $client->set('key', 'hello world');
    $value = $client->get('key');

    echo "The value of key is: {$value}";

    This code creates a key named key with the value hello world without an expiration. It then retrieves this key from the Valkey service and outputs its value.

  2. Run the script using the following command:

    php index.php

    A successful connection displays:

    The value of key is: hello world