Skip to content

Redis - Php

Integrating Redis into a modern PHP application is straightforward using Composer for dependency management. You have two main choices for a Redis client:

  • PhpRedis: A PHP extension written in C. It’s extremely fast but requires installation on the server (e.g., via PECL).
  • Predis: A pure PHP client library. It’s slightly slower but requires no special extensions, just a composer require.

For new projects, starting with Predis is often easiest. We will use Predis for these examples.

In your project directory, run the following command to add Predis to your project:

composer require predis/predis

Then, include Composer’s autoloader in your PHP script.

<?php
require 'vendor/autoload.php';

Instantiate the Predis client. It’s good practice to wrap your Redis logic in a try...catch block to handle potential connection errors.

<?php
require 'vendor/autoload.php';
try {
$redis = new Predis\Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
]);
echo "Connection to server successfully" . PHP_EOL;
// Check connection
$ping = $redis->ping();
echo "Server is running: " . $ping . PHP_EOL;
} catch (Exception $e) {
die("Could not connect to Redis: " . $e->getMessage());
}

When the program is executed, it will produce the following result:

Connection to server successfully
Server is running: PONG

The following examples assume you have a $redis client object as shown above.

<?php
// ... (autoloader and connection)
$key = 'tutorial-name';
$value = 'Modern Redis with PHP';
$redis->set($key, $value);
$retrievedValue = $redis->get($key);
echo "Stored string in redis: " . $retrievedValue . PHP_EOL;
<?php
// ... (autoloader and connection)
$listKey = 'frameworks';
// Clear old list items before running example
$redis->del($listKey);
$redis->lpush($listKey, ['Laravel', 'Symfony', 'Yii']);
$frameworks = $redis->lrange($listKey, 0, -1);
echo "PHP Frameworks: " . PHP_EOL;
print_r($frameworks);

Warning: Never use KEYS * in production as it can block your server. The safe, modern alternative is to use an iterator which leverages the SCAN command.

<?php
// ... (autoloader and connection)
use Predis\Collection\Iterator\Keyspace;
// Add some sample keys for the demo
$redis->set('user:1', 'Alice');
$redis->set('user:2', 'Bob');
$redis->set('config:theme', 'dark');
echo "\nScanning for keys with pattern 'user:*':" . PHP_EOL;
$matchingKeys = [];
// Predis provides a convenient iterator that handles the SCAN logic internally
foreach (new Keyspace($redis, 'user:*') as $key) {
$matchingKeys[] = $key;
}
print_r($matchingKeys);

In large applications, you will typically interact with Redis through an abstraction layer provided by a framework like Laravel or Symfony. They handle the configuration, connection pooling, and provide a clean, fluent API for caching, session handling, and queueing with Redis.