Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

phpredis

> 数据库
Open source

A PHP extension for Redis

10.2K stars0 likes1 views
WebsiteGitHub

About

A PHP extension for Redis

PhpRedis

The phpredis extension provides an API for communicating with the Redis key-value store. Valkey, Dragonfly, and KeyDB are supported as well.

It is released under the PHP License, version 3.01.

You can send comments, patches, questions here on github, to Michael (Twitter, Mastodon), Pavlo (@yatsukhnenko), or Nicolas (@yowgi).

Sponsors

Become a Sponsor

PhpRedis will always be free and open source software and if you or your company has found it useful please consider supporting the project. Developing a large, complex, and performant library like PhpRedis takes a great deal of time and effort, and support is greatly appreciated! :heart:

The ongoing development of PhpRedis is made possible thanks to the generous support of Relay, which funds the vast majority of work on the project. Relay is a high-performance in-memory cache and drop-in replacement for PhpRedis, which handles millions of requests per second without breaking a sweat.

The best way to support the project is through GitHub Sponsors. Many of the reward tiers grant access to our Slack where myself and Pavlo are regularly available to answer questions. Additionally this will allow you to provide feedback on which fixes and features to prioritize. You can also make a one-time contribution with PayPal.

Table of contents

  1. Installing/Configuring
    • Installation
    • PHP Session handler
    • Distributed Redis Array
    • Redis Cluster support
    • Redis Sentinel support
    • Running the unit tests
  2. API Documentation
  3. Classes and methods
    • Usage
    • Connection
    • Retry and backoff
    • Server
    • Keys and strings
    • Hashes
    • Lists
    • Sets
    • Sorted sets
    • HyperLogLogs
    • Geocoding
    • Streams
    • Pub/sub
    • Transactions
    • Scripting
    • Local Helper Methods
    • Introspection

Installing/Configuring

Installation

For everything you should need to install PhpRedis on your system, see the INSTALL.md page.

PHP Session handler

phpredis can be used to store PHP sessions. To do this, configure session.save_handler and session.save_path in your php.ini to tell phpredis where to store the sessions.

session.save_path can have a simple host:port format too, but you need to provide the tcp:// scheme if you want to use the parameters. The following parameters are available:

  • weight (integer): the weight of a host is used in comparison with the others to customize the session distribution on several hosts. If host A has twice the weight of host B, it will get twice the amount of sessions. In the example, host1 stores 20% of all the sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/(1+2+2)). The target host is determined once and for all at the start of the session, and doesn't change. The default weight is 1.
  • timeout (float): the connection timeout to a redis host, expressed in seconds. If the host is unreachable in that amount of time, the session storage will be unavailable for the client. The default timeout is very high (86400 seconds).
  • read_timeout (float): the timeout for read operations on an established connection, expressed in seconds. If a Redis response is not received within this time, the session operation fails. The default is 0 (no timeout), meaning PHP can hang indefinitely if Redis becomes unresponsive or a connection goes stale. Setting this to a low value (e.g. 2.5) is strongly recommended in production environments.
  • persistent (integer, should be 1 or 0): defines if a persistent connection should be used. The default value is 0 (persistent connection is not used).
  • prefix (string, defaults to "PHPREDIS_SESSION:"): used as a prefix to the Redis key in which the session is stored. The key is composed of the prefix followed by the session ID.
  • auth (string, or an array with one or two elements): used to authenticate with the server prior to sending commands.
  • database (integer): selects a different database.

Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime". You can change it with ini_set(). The session handler requires a version of Redis supporting EX and NX options of SET command (at least 2.6.12). phpredis can also connect to a unix domain socket: session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0".

Examples

Multiple Redis servers:

session.save_handler = redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2&read_timeout=2.5"

Login to Redis using username and password:

session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?auth[]=user&auth[]=password"

Login to Redis using username, password, and set prefix:

session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379?auth[]=user&auth[]=password&prefix=user_PHPREDIS_SESSION:"

Session locking

Support: Locking feature is currently only supported for Redis setup with single master instance (e.g. classic master/slave Sentinel environment). So locking may not work properly in RedisArray or RedisCluster environments.

The following INI variables can be used to configure session locking:

; Should the locking be enabled? Defaults to: 0.
redis.session.locking_enabled = 1
; How long should the lock live (in seconds)? Defaults to: value of max_execution_time.
redis.session.lock_expire = 60
; How long to wait between attempts to acquire lock, in microseconds (µs)?. Defaults to: 20000
redis.session.lock_wait_time = 50000
; Maximum number of times to retry (-1 means infinite). Defaults to: 100
redis.session.lock_retries = 2000

Session compression

The following INI variables can be used to configure session compression:

; Should session compression be enabled? Possible values are zstd, lzf, lz4, none. Defaults to: none
redis.session.compression = zstd
; What compression level should be used? Compression level depends on used library. For most deployments range 1-9 should be fine. Defaults to: 3
redis.session.compression_level = 3

Running the unit tests

phpredis uses a small custom unit test suite for testing functionality of the various classes. To run tests, simply do the following:

# Run tests for Redis class (note this is the default)
php tests/TestRedis.php --class Redis

# Run tests for RedisArray class
tests/mkring.sh start
php tests/TestRedis.php --class RedisArray
tests/mkring.sh stop

# Run tests for the RedisCluster class
tests/make-cluster.sh start
php tests/TestRedis.php --class RedisCluster
tests/make-cluster.sh stop

# Run tests for RedisSentinel class
php tests/TestRedis.php --class RedisSentinel

Note that it is possible to filter tests by a substring of the test itself by passing the additional argument '--test ' when invoking. Multiple test filters can be provided either as a comma-separated list, with repeated --test arguments, or by combining both forms. Prefix a filter with ! to exclude matching tests. Exclusions take precedence over inclusions, and when only exclusions are provided all other tests run.

# Just run the 'echo' test
php tests/TestRedis.php --class Redis --test echo

# Run tests matching 'get', 'set', or 'echo'
php tests/TestRedis.php --class Redis --test get,set --test echo

# Run tests matching 'get' or 'set', except those matching 'range'
php tests/TestRedis.php --class Redis --test 'get,set,!range'

# Run every test except those matching 'commandstats'
php tests/TestRedis.php --class Redis --test '!commandstats'

API Documentation

The API Documentation are a work in progress, but will eventually replace our ONE README TO RULE THEM ALL docs.

Classes and methods

Usage

  1. Class Redis
  2. Class RedisException
  3. Predefined constants

Class Redis


Description: Creates a Redis client

Example
php
$redis = new Redis();

Starting from version 6.0.0 it's possible to specify configuration options. This allows to connect lazily to the server without explicitly invoking connect / pconnect.

Example
php
$redis = new Redis([
    'host' => '127.0.0.1',
    'port' => 6379,
    'connectTimeout' => 2.5,
    'auth' => ['phpredis', 'phpredis'],
    'database' => 2,
    'ssl' => ['verify_peer' => false],
    'backoff' => [
        'algorithm' => Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER,
        'base' => 500,
        'cap' => 750,
    ],
]);
Parameters (optional)

host: string, the hostname/FQDN/IP address or the path to a unix domain socket; since v5.0.0 it is possible to specify schema port: int, actual port (e.g. 6379) or -1 (or 0) for unix domain socket; setting to < 0 with non-UDS will assume default of 6379 connectTimeout: float, value in seconds (default is 0 meaning unlimited) retryInterval: int, value in milliseconds (optional) readTimeout: float, value in seconds (default is 0 meaning unlimited) persistent: mixed, If the value is a string it is used as a persistent ID. Non-strings are cast to boolean. auth: mixed, authentication information database: int, database number ssl: array, SSL context options

Class RedisException


phpredis throws a RedisException object if it can't reach the Redis server. That can happen in case of connectivity issues, if the Redis service is down, or if the Redis host is overloaded. In any other problematic case that does not involve an unreachable server (such as a key not existing, an invalid command, etc), phpredis will return FALSE.

Predefined constants


Description: Available Redis Constants

Redis data types, as returned by type

Redis::REDIS_STRING - String
Redis::REDIS_SET - Set
Redis::REDIS_LIST - List
Redis::REDIS_ZSET - Sorted set
Redis::REDIS_HASH - Hash
Redis::REDIS_STREAM - Stream    
Redis::REDIS_VECTORSET - Vector set
Redis::REDIS_NOT_FOUND - Not found / other

Connection

  1. connect, open - Connect to a server
  2. pconnect, popen - Connect to a server (persistent)
  3. auth - Authenticate to the server
  4. select - Change the selected database for the current connection
  5. swapdb - Swaps two Redis databases
  6. close - Close the connection
  7. setOption - Set client option
  8. getOption - Get client option
  9. ping - Ping the server
  10. echo - Echo the given string

connect, open


Description: Connects to a Redis instance. If phpredis cannot reach the server it will usually throw a RedisException; only rarely will FALSE be returned

Issues· 135 open

View all issuesOpen on GitHub
  • #2931

    Reconnect inside a pipeline drops its replies and desyncs persistent connections

    Updated Sep 18, 2026
  • #2897

    Implement `INCREX` (Redis 8.8.0)

    Updated Jul 30, 2026
  • #2893

    [RFC] Add support for setting SETNAME lazy

    Updated Jul 21, 2026
  • #2543

    Redis 8.0 support for new data structures/commands

    Updated Jun 11, 2026
  • #2715

    Add `SELECT` command to `RedisCluster`.

    improvementvalkeyUpdated Jun 8, 2026
  • #2062

    Failed to use mTLS with PHP Session handler (redis mode)

    Updated Jun 5, 2026
  • #2839

    SIGINT ignored in brPop()

    Updated May 13, 2026
  • #2352

    With compression the `Redis::SERIALIZER_JSON` serializer is not working

    bugUpdated May 1, 2026
  • #2819

    Proposal: Native multi-host support for RedisSentinel

    Updated May 1, 2026
  • #2829

    protocol error got as reply type byte

    Updated Apr 20, 2026

> Tags

Cclusterkeydbphpredis

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库