SkillAgentSearch skills...

Predis

A flexible and feature-complete Redis/Valkey client for PHP.

Install / Use

/learn @predis/Predis
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Predis

![Software license][ico-license] [![Latest stable][ico-version-stable]][link-releases] [![Latest development][ico-version-dev]][link-releases] [![Monthly installs][ico-downloads-monthly]][link-downloads] [![Build status][ico-build]][link-actions] [![Coverage Status][ico-coverage]][link-coverage]

A flexible and feature-complete Redis / Valkey client for PHP 7.2 and newer.

More details about this project can be found on the frequently asked questions.

Main features

  • Support for Redis from 3.0 to 8.0.
  • Support for clustering using client-side sharding and pluggable keyspace distributors.
  • Support for redis-cluster (Redis >= 3.0).
  • Support for master-slave replication setups and redis-sentinel.
  • Transparent key prefixing of keys using a customizable prefix strategy.
  • Command pipelining on both single nodes and clusters (client-side sharding only).
  • Abstraction for Redis transactions (Redis >= 2.0) and CAS operations (Redis >= 2.2).
  • Abstraction for Lua scripting (Redis >= 2.6) and automatic switching between EVALSHA or EVAL.
  • Abstraction for SCAN, SSCAN, ZSCAN and HSCAN (Redis >= 2.8) based on PHP iterators.
  • Connections are established lazily by the client upon the first command and can be persisted.
  • Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets.
  • Support for custom connection classes for providing different network or protocol backends.
  • Flexible system for defining custom commands and override the default ones.

How to install and use Predis

This library can be found on Packagist for an easier management of projects dependencies using Composer. Compressed archives of each release are available on GitHub.

composer require predis/predis

Loading the library

Predis relies on the autoloading features of PHP to load its files when needed and complies with the PSR-4 standard. Autoloading is handled automatically when dependencies are managed through Composer, but it is also possible to leverage its own autoloader in projects or scripts lacking any autoload facility:

// Prepend a base path if Predis is not available in your "include_path".
require 'Predis/Autoloader.php';

Predis\Autoloader::register();

Connecting to Redis

When creating a client instance without passing any connection parameter, Predis assumes 127.0.0.1 and 6379 as default host and port. The default timeout for the connect() operation is 5 seconds:

$client = new Predis\Client();
$client->set('foo', 'bar');
$value = $client->get('foo');

Connection parameters can be supplied either in the form of URI strings or named arrays. The latter is the preferred way to supply parameters, but URI strings can be useful when parameters are read from non-structured or partially-structured sources:

// Parameters passed using a named array:
$client = new Predis\Client([
    'scheme' => 'tcp',
    'host'   => '10.0.0.1',
    'port'   => 6379,
]);

// Same set of parameters, passed using an URI string:
$client = new Predis\Client('tcp://10.0.0.1:6379');

Password protected servers can be accessed by adding password to the parameters set. When ACLs are enabled on Redis >= 6.0, both username and password are required for user authentication.

It is also possible to connect to local instances of Redis using UNIX domain sockets, in this case the parameters must use the unix scheme and specify a path for the socket file:

$client = new Predis\Client(['scheme' => 'unix', 'path' => '/path/to/redis.sock']);
$client = new Predis\Client('unix:/path/to/redis.sock');

The client can leverage TLS/SSL encryption to connect to secured remote Redis instances without the need to configure an SSL proxy like stunnel. This can be useful when connecting to nodes running on various cloud hosting providers. Encryption can be enabled with using the tls scheme and an array of suitable options passed via the ssl parameter:

// Named array of connection parameters:
$client = new Predis\Client([
  'scheme' => 'tls',
  'ssl'    => ['cafile' => 'private.pem', 'verify_peer' => true],
]);

// Same set of parameters, but using an URI string:
$client = new Predis\Client('tls://127.0.0.1?ssl[cafile]=private.pem&ssl[verify_peer]=1');

The connection schemes redis (alias of tcp) and rediss (alias of tls) are also supported, with the difference that URI strings containing these schemes are parsed following the rules described on their respective IANA provisional registration documents.

Since Redis 8.6, you can authenticate a client using the Subject CN from its TLS client certificate (mTLS). When this is enabled on the server, the client is authenticated during the TLS handshake, so you don’t need to send an AUTH command.

To use this, configure:

  • a CA certificate used to verify the server certificate (cafile),
  • a client certificate (local_cert) signed by a CA trusted by the Redis server for client authentication,
  • the corresponding private key (local_pk).

Make sure:

  • the Redis server certificate is signed by a CA trusted by the client, and
  • the client certificate is signed by a CA trusted by the Redis server (mTLS).
// Named array of connection parameters:
$client = new Predis\Client([
    'scheme' => 'tls',
    'ssl' => [
        'cafile'      => 'ca.pem',          // CA used to verify the server certificate
        'local_cert'  => 'client.crt',      // client certificate (Subject CN maps to ACL user)
        'local_pk'    => 'client.key',      // client private key
        'verify_peer' => true,
    ],
]);

// ACL user must exist and match the certificate Subject CN (example: CN=CN_NAME).
// Enable the user and grant permissions as needed:
$client->acl->setUser('CN_NAME', 'on', '>clientpass', 'allcommands', 'allkeys')

echo $client->acl->whoami() // CN_NAME

The actual list of supported connection parameters can vary depending on each connection backend so it is recommended to refer to their specific documentation or implementation for details.

Predis can aggregate multiple connections when providing an array of connection parameters and the appropriate option to instruct the client about how to aggregate them (clustering, replication or a custom aggregation logic). Named arrays and URI strings can be mixed when providing configurations for each node:

$client = new Predis\Client([
    'tcp://10.0.0.1?alias=first-node', ['host' => '10.0.0.2', 'alias' => 'second-node'],
], [
    'cluster' => 'predis',
]);

See the aggregate connections section of this document for more details.

Connections to Redis are lazy meaning that the client connects to a server only if and when needed. While it is recommended to let the client do its own stuff under the hood, there may be times when it is still desired to have control of when the connection is opened or closed: this can easily be achieved by invoking $client->connect() and $client->disconnect(). Please note that the effect of these methods on aggregate connections may differ depending on each specific implementation.

Persistent connections

To increase a performance of your application you may set up a client to use persistent TCP connection, this way client saves a time on socket creation and connection handshake. By default, connection is created on first-command execution and will be automatically closed by GC before the process is being killed. However, if your application is backed by PHP-FPM the processes are idle, and you may set up it to be persistent and reusable across multiple script execution within the same process.

To enable the persistent connection mode you should provide following configuration:

// Standalone
$client = new Predis\Client(['persistent' => true]);

// Cluster
$client = new Predis\Client(
    ['tcp://host:port', 'tcp://host:port', 'tcp://host:port'],
    ['cluster' => 'redis', 'parameters' => ['persistent' => true]]
);

Important

If you operate on multiple clients within the same application, and they communicate with the same resource, by default they will share the same socket (that's the default behaviour of persistent sockets). So in this case you would need to additionally provide a conn_uid identifier for each client, this way each client will create its own socket so the connection context won't be shared across clients. This socket behaviour explained here

// Standalone
$client1 = new Predis\Client(['persistent' => true, 'conn_uid' => 'id_1']);
$client2 = new Predis\Client(['persistent' => true, 'conn_uid' => 'id_2']);

// Cluster
$client1 = new Predis\Client(
    ['tcp://host:port', 'tcp://host:port', 'tcp://host:port'],
    ['cluster' => 'redis', 'parameters' => ['persistent' => true, 'conn_uid' => 'id_1']]
);
$client2 = new Predis\Client(
    ['tcp://host:port', 'tcp://host:port', 'tcp://host:port'],
    ['cluster' => 'redis', 'parameters' => ['persistent' => true, 'conn_uid' => 'id_2']]
);

Client configuration

Many aspects and behaviors of the client can be configured by passing specific client options to the second argument of Predis\Client::__construct():

$client = new Predis\Client($parameters, ['prefix' => 'sample:']);

Options are managed using a mini DI-alike container

View on GitHub
GitHub Stars7.8k
CategoryDevelopment
Updated1d ago
Forks994

Languages

PHP

Security Score

100/100

Audited on Mar 28, 2026

No findings