The phpredis extension provides an API for communicating with the Redis key-value store. It is released under the PHP License, version 3.01. This code has been developed and maintained by Owlient from November 2009 to March 2011.
You can send comments, patches, questions here on github, to n.favrefelix@gmail.com (@yowgi), to michael.grunder@gmail.com (@grumi78) or to p.yatsukhnenko@gmail.com (@yatsukhnenko).
PhpRedis will always be free and open source software, but 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 would be appreciated! ❤️
The best way to support the project is through GitHub sponsors. Many of the reward tiers grant access to our slack channel where myself and Pavlo are regularly available to answer questions. Additionally this will allow you to provide feedback on which fixes and new features to prioritize.
You can also make a one-time contribution with one of the links below.
For everything you should need to install PhpRedis on your system, see the INSTALL.markdown page.
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_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"
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 in order 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).
- persistent (integer, should be 1 or 0): defines if a persistent connection should be used. (experimental setting)
- 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"
.
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.
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: 2000
redis.session.lock_wait_time = 50000
; Maximum number of times to retry (-1 means infinite). Defaults to: 10
redis.session.lock_retries = 10
See dedicated page.
See dedicated page.
See dedicated page.
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 run only tests which match a substring of the test itself by passing the additional argument '--test ' when invoking.
# Just run the 'echo' test
php tests/TestRedis.php --class Redis --test echo
Description: Creates a Redis client
$redis = new Redis();
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
10000
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
.
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_NOT_FOUND - Not found / other
@TODO: OPT_SERIALIZER, AFTER, BEFORE,...
- connect, open - Connect to a server
- pconnect, popen - Connect to a server (persistent)
- auth - Authenticate to the server
- select - Change the selected database for the current connection
- swapdb - Swaps two Redis databases
- close - Close the connection
- setOption - Set client option
- getOption - Get client option
- ping - Ping the server
- echo - Echo the given string
Description: Connects to a Redis instance.
host: string. can be a host, or the path to a unix domain socket. Starting from version 5.0.0 it is possible to specify schema
port: int, optional
timeout: float, value in seconds (optional, default is 0 meaning unlimited)
reserved: should be NULL if retry_interval is specified
retry_interval: int, value in milliseconds (optional)
read_timeout: float, value in seconds (optional, default is 0 meaning unlimited)
BOOL: TRUE
on success, FALSE
on error.
$redis->connect('127.0.0.1', 6379);
$redis->connect('127.0.0.1'); // port 6379 by default
$redis->connect('tls://127.0.0.1', 6379); // enable transport level security.
$redis->connect('tls://127.0.0.1'); // enable transport level security, port 6379 by default.
$redis->connect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout.
$redis->connect('/tmp/redis.sock'); // unix domain socket.
$redis->connect('127.0.0.1', 6379, 1, NULL, 100); // 1 sec timeout, 100ms delay between reconnection attempts.
/* With PhpRedis >= 5.3.0 you can specify authentication information on connect */
$redis->connect('127.0.0.1', 6379, 1, NULL, 0, 0, ['auth' => ['phpredis', 'phpredis']]);
Note: open
is an alias for connect
and will be removed in future versions of phpredis.
Description: Connects to a Redis instance or reuse a connection already established with pconnect
/popen
.
The connection will not be closed on end of request until the php process ends. So be prepared for too many open FD's errors (specially on redis server side) when using persistent connections on many servers connecting to one redis server.
Also more than one persistent connection can be made identified by either host + port + timeout or host + persistent_id or unix socket + timeout.
Starting from version 4.2.1, it became possible to use connection pooling by setting INI variable redis.pconnect.pooling_enabled
to 1.
This feature is not available in threaded versions. pconnect
and popen
then working like their non
persistent equivalents.
host: string. can be a host, or the path to a unix domain socket. Starting from version 5.0.0 it is possible to specify schema
port: int, optional
timeout: float, value in seconds (optional, default is 0 meaning unlimited)
persistent_id: string. identity for the requested persistent connection
retry_interval: int, value in milliseconds (optional)
read_timeout: float, value in seconds (optional, default is 0 meaning unlimited)
BOOL: TRUE
on success, FALSE
on error.
$redis->pconnect('127.0.0.1', 6379);
$redis->pconnect('127.0.0.1'); // port 6379 by default - same connection like before.
$redis->pconnect('tls://127.0.0.1', 6379); // enable transport level security.
$redis->pconnect('tls://127.0.0.1'); // enable transport level security, port 6379 by default.
$redis->pconnect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout and would be another connection than the two before.
$redis->pconnect('127.0.0.1', 6379, 2.5, 'x'); // x is sent as persistent_id and would be another connection than the three before.
$redis->pconnect('/tmp/redis.sock'); // unix domain socket - would be another connection than the four before.
Note: popen
is an alias for pconnect
and will be removed in future versions of phpredis.
Description: Authenticate the connection using a password or a username and password. Warning: The password is sent in plain-text over the network.
MIXED: password
BOOL: TRUE
if the connection is authenticated, FALSE
otherwise.
Note: In order to authenticate with a username and password you need Redis >= 6.0.
/* Authenticate with the password 'foobared' */
$redis->auth('foobared');
/* Authenticate with the username 'phpredis', and password 'haxx00r' */
$redis->auth(['phpredis', 'haxx00r']);
/* Authenticate with the password 'foobared' */
$redis->auth(['foobared']);
/* You can also use an associative array specifying user and pass */
$redis->auth(['user' => 'phpredis', 'pass' => 'phpredis']);
$redis->auth(['pass' => 'phpredis']);
Description: Change the selected database for the current connection.
INTEGER: dbindex, the database number to switch to.
TRUE
in case of success, FALSE
in case of failure.
See method for example: move
Description: Swap one Redis database with another atomically
INTEGER: db1
INTEGER: db2
TRUE
on success and FALSE
on failure.
Note: Requires Redis >= 4.0.0
$redis->swapdb(0, 1); /* Swaps DB 0 with DB 1 atomically */
Description: Disconnects from the Redis instance.
Note: Closing a persistent connection requires PhpRedis >= 4.2.0.
None.
BOOL: TRUE
on success, FALSE
on failure.
Description: Set client option.
parameter name
parameter value
BOOL: TRUE
on success, FALSE
on error.
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // Don't serialize data
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // Use built-in serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // Use igBinary serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_MSGPACK); // Use msgpack serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_JSON); // Use JSON to serialize/unserialize
$redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys
/* Options for the SCAN family of commands, indicating whether to abstract
empty results from the user. If set to SCAN_NORETRY (the default), phpredis
will just issue one SCAN command at a time, sometimes returning an empty
array of results. If set to SCAN_RETRY, phpredis will retry the scan command
until keys come back OR Redis returns an iterator of zero
*/
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
/* Scan can also be configured to automatically prepend the currently set PhpRedis
prefix to any MATCH pattern. */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_PREFIX);
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NOPREFIX);
Description: Get client option.
parameter name
Parameter value.
// return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP,
// Redis::SERIALIZER_IGBINARY, Redis::SERIALIZER_MSGPACK or Redis::SERIALIZER_JSON
$redis->getOption(Redis::OPT_SERIALIZER);
Description: Check the current connection status.
$redis->ping([string $message]);
Mixed: This method returns TRUE
on success, or the passed string if called with an argument.
/* When called without an argument, PING returns `TRUE` */
$redis->ping();
/* If passed an argument, that argument is returned. Here 'hello' will be returned */
$redis->ping('hello');
Note: Prior to PhpRedis 5.0.0 this command simply returned the string +PONG
.
Description: Sends a string to Redis, which replies with the same string
STRING: The message to send.
STRING: the same message.
You can set and get the maximum retries upon connection issues using the OPT_MAX_RETRIES
option. Note that this is the number of retries, meaning if you set this option to n, there will be a maximum n+1 attemps overall. Defaults to 10.
$redis->setOption(Redis::OPT_MAX_RETRIES, 5);
$redis->getOption(Redis::OPT_MAX_RETRIES);
You can set the backoff algorithm using the Redis::OPT_BACKOFF_ALGORITHM
option and choose among the following algorithms described in this blog post by Marc Brooker from AWS: Exponential Backoff And Jitter:
- Default:
Redis::BACKOFF_ALGORITHM_DEFAULT
- Decorrelated jitter:
Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER
- Full jitter:
Redis::BACKOFF_ALGORITHM_FULL_JITTER
- Equal jitter:
Redis::BACKOFF_ALGORITHM_EQUAL_JITTER
- Exponential:
Redis::BACKOFF_ALGORITHM_EXPONENTIAL
- Uniform:
Redis::BACKOFF_ALGORITHM_UNIFORM
- Constant:
Redis::BACKOFF_ALGORITHM_CONSTANT
These algorithms depend on the base and cap parameters, both in milliseconds, which you can set using the Redis::OPT_BACKOFF_BASE
and Redis::OPT_BACKOFF_CAP
options, respectively.
$redis->setOption(Redis::OPT_BACKOFF_ALGORITHM, Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER);
$redis->setOption(Redis::OPT_BACKOFF_BASE, 500); // base for backoff computation: 500ms
$redis->setOption(Redis::OPT_BACKOFF_CAP, 750); // backoff time capped at 750ms
- acl - Manage Redis ACLs
- bgRewriteAOF - Asynchronously rewrite the append-only file
- bgSave - Asynchronously save the dataset to disk (in background)
- config - Get or Set the Redis server configuration parameters
- dbSize - Return the number of keys in selected database
- flushAll - Remove all keys from all databases
- flushDb - Remove all keys from the current database
- info - Get information and statistics about the server
- lastSave - Get the timestamp of the last disk save
- resetStat - Reset the stats returned by info method.
- save - Synchronously save the dataset to disk (wait to complete)
- slaveOf - Make the server a slave of another instance, or promote it to master
- time - Return the current server time
- slowLog - Access the Redis slowLog entries
Description: Execute the Redis ACL command.
variable: Minumum of one argument for Redis
and two for RedisCluster
.
$redis->acl('USERS'); /* Get a list of users */
$redis->acl('LOG'); /* See log of Redis' ACL subsystem */
Note: In order to user the ACL
command you must be communicating with Redis >= 6.0 and be logged into an account that has access to administration commands such as ACL. Please reference this tutorial for an overview of Redis 6 ACLs and the redis command reference for every ACL subcommand.
Note: If you are connecting to Redis server >= 4.0.0 you can remove a key with the unlink
method in the exact same way you would use del
. The Redis unlink command is non-blocking and will perform the actual deletion asynchronously.
Description: Start the background rewrite of AOF (Append-Only File)
None.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->bgRewriteAOF();
Description: Asynchronously save the dataset to disk (in background)
None.
BOOL: TRUE
in case of success, FALSE
in case of failure. If a save is already running, this command will fail and return FALSE
.
$redis->bgSave();
Description: Get or Set the Redis server configuration parameters.
operation (string) either GET
or SET
key string for SET
, glob-pattern for GET
. See http://redis.io/commands/config-get for examples.
value optional string (only for SET
)
Associative array for GET
, key -> value
bool for SET
$redis->config("GET", "*max-*-entries*");
$redis->config("SET", "dir", "/var/run/redis/dumps/");
Description: Return the number of keys in selected database.
None.
INTEGER: DB size, in number of keys.
$count = $redis->dbSize();
echo "Redis has $count keys\n";
Description: Remove all keys from all databases.
async (bool) requires server version 4.0.0 or greater
BOOL: Always TRUE
.
$redis->flushAll();
Description: Remove all keys from the current database.
async (bool) requires server version 4.0.0 or greater
BOOL: Always TRUE
.
$redis->flushDb();
Description: Get information and statistics about the server
Returns an associative array that provides information about the server. Passing no arguments to INFO will call the standard REDIS INFO command, which returns information such as the following:
- redis_version
- arch_bits
- uptime_in_seconds
- uptime_in_days
- connected_clients
- connected_slaves
- used_memory
- changes_since_last_save
- bgsave_in_progress
- last_save_time
- total_connections_received
- total_commands_processed
- role
You can pass a variety of options to INFO (per the Redis documentation), which will modify what is returned.
option: The option to provide redis (e.g. "COMMANDSTATS", "CPU")
$redis->info(); /* standard redis INFO command */
$redis->info("COMMANDSTATS"); /* Information on the commands that have been run (>=2.6 only)
$redis->info("CPU"); /* just CPU information from Redis INFO */
Description: Returns the timestamp of the last disk save.
None.
INT: timestamp.
$redis->lastSave();
Description: Reset the stats returned by info method.
These are the counters that are reset:
- Keyspace hits
- Keyspace misses
- Number of commands processed
- Number of connections received
- Number of expired keys
None.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->resetStat();
Description: Synchronously save the dataset to disk (wait to complete)
None.
BOOL: TRUE
in case of success, FALSE
in case of failure. If a save is already running, this command will fail and return FALSE
.
$redis->save();
Description: Changes the slave status
Either host (string) and port (int), or no parameter to stop being a slave.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->slaveOf('10.0.1.7', 6379);
/* ... */
$redis->slaveOf();
Description: Return the current server time.
(none)
If successful, the time will come back as an associative array with element zero being the unix timestamp, and element one being microseconds.
$redis->time();
Description: Access the Redis slowLog
Operation (string): This can be either GET
, LEN
, or RESET
Length (integer), optional: If executing a SLOWLOG GET
command, you can pass an optional length.
The return value of SLOWLOG will depend on which operation was performed. SLOWLOG GET: Array of slowLog entries, as provided by Redis SLOGLOG LEN: Integer, the length of the slowLog SLOWLOG RESET: Boolean, depending on success
// Get ten slowLog entries
$redis->slowLog('get', 10);
// Get the default number of slowLog entries
$redis->slowLog('get');
// Reset our slowLog
$redis->slowLog('reset');
// Retrieve slowLog length
$redis->slowLog('len');
- append - Append a value to a key
- bitCount - Count set bits in a string
- bitOp - Perform bitwise operations between strings
- decr, decrBy - Decrement the value of a key
- get - Get the value of a key
- getBit - Returns the bit value at offset in the string value stored at key
- getRange - Get a substring of the string stored at a key
- getSet - Set the string value of a key and return its old value
- incr, incrBy - Increment the value of a key
- incrByFloat - Increment the float value of a key by the given amount
- mGet, getMultiple - Get the values of all the given keys
- mSet, mSetNX - Set multiple keys to multiple values
- set - Set the string value of a key
- setBit - Sets or clears the bit at offset in the string value stored at key
- setEx, pSetEx - Set the value and expiration of a key
- setNx - Set the value of a key, only if the key does not exist
- setRange - Overwrite part of a string at key starting at the specified offset
- strLen - Get the length of the value stored in a key