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.
These are a work in progress, but will eventually replace our ONE README TO RULE THEM ALL docs.
Supporting the project
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.
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 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.
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".
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.
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
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 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
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 command.
host: string. can be a host, or the path to a unix domain socket. port: int (default is 6379, should be -1 for unix domain socket) 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 value is string then it used as persistend id, else value casts to boolean auth: mixed, authentication information 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.
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
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 it will use default_socket_timeout) reserved: should be '' if retry_interval is specified retry_interval: int, value in milliseconds (optional) read_timeout: float, value in seconds (optional, default is 0 meaning it will use default_socket_timeout) others: array, with PhpRedis >= 5.3.0, it allows setting auth and stream configuration.
Return value
BOOL: TRUE on success, FALSE on error.
Example
$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, '', 100); // 1 sec timeout, 100ms delay between reconnection attempts.$redis->connect('/tmp/redis.sock', 0, 1.5, NULL, 0, 1.5); // Unix socket with 1.5s timeouts (connect and read)/* With PhpRedis >= 5.3.0 you can specify authentication and stream information on connect */$redis->connect('127.0.0.1', 6379, 1, '', 0, 0, ['auth' => ['phpredis', 'phpredis']]);
Note:open is an alias for connect and will be removed in future versions of phpredis.
pconnect, popen
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.
Parameters
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 it will use default_socket_timeout) 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 it will use default_socket_timeout)
Return value
BOOL: TRUE on success, FALSE on error.
Example
$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.
auth
Description: Authenticate the connection using a password or a username and password.
Warning: The password is sent in plain-text over the network.
Parameters
MIXED: password
Return value
BOOL: TRUE if the connection is authenticated, FALSE otherwise.
Note: In order to authenticate with a username and password you need Redis >= 6.0.
Example
/* 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']);
select
Description: Change the selected database for the current connection.
Parameters
INTEGER: dbindex, the database number to switch to.
Return value
TRUE in case of success, FALSE in case of failure.
Description: Swap one Redis database with another atomically
Parameters
INTEGER: db1 INTEGER: db2
Return value
TRUE on success and FALSE on failure.
Note: Requires Redis >= 4.0.0
Example
$redis->swapdb(0, 1); /* Swaps DB 0 with DB 1 atomically */
close
Description: Disconnects from the Redis instance.
Note: Closing a persistent connection requires PhpRedis >= 4.2.0.
Parameters
None.
Return value
BOOL: TRUE on success, FALSE on failure.
setOption
Description: Set client option.
Parameters
parameter name parameter value
Return value
BOOL: TRUE on success, FALSE on error.
Example
$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);
getOption
Description: Get client option.
Parameters
parameter name
Return value
Parameter value.
Example
// return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, // Redis::SERIALIZER_IGBINARY, Redis::SERIALIZER_MSGPACK or Redis::SERIALIZER_JSON$redis->getOption(Redis::OPT_SERIALIZER);
ping
Description: Check the current connection status.
Prototype
$redis->ping([string $message]);
Return value
Mixed: This method returns TRUE on success, or the passed string if called with an argument.
Example
/* 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.
echo
Description: Sends a string to Redis, which replies with the same string
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.
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:
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.
Example
$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
variable: Minumum of one argument for Redis and two for RedisCluster.
Example
$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.
bgRewriteAOF
Description: Start the background rewrite of AOF (Append-Only File)
Parameters
None.
Return value
BOOL: TRUE in case of success, FALSE in case of failure.
Example
$redis->bgRewriteAOF();
bgSave
Description: Asynchronously save the dataset to disk (in background)
Parameters
None.
Return value
BOOL: TRUE in case of success, FALSE in case of failure. If a save is already running, this command will fail and return FALSE.
Example
$redis->bgSave();
config
Description: Get or Set the Redis server configuration parameters.
Description: Return the number of keys in selected database.
Parameters
None.
Return value
INTEGER: DB size, in number of keys.
Example
$count = $redis->dbSize();
echo "Redis has $count keys\n";
flushAll
Description: Remove all keys from all databases.
Parameters
async (bool) requires server version 4.0.0 or greater
Return value
BOOL: Always TRUE.
Example
$redis->flushAll();
flushDb
Description: Remove all keys from the current database.
Prototype
$redis->flushdb(?bool $sync = NULL): Redis|bool;
Return value
BOOL: This command returns true on success and false on failure.
Example
$redis->flushDb();
info
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.
Parameters
option: The option to provide redis (e.g. "COMMANDSTATS", "CPU")
Example
$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 */
lastSave
Description: Returns the timestamp of the last disk save.
Parameters
None.
Return value
INT: timestamp.
Example
$redis->lastSave();
save
Description: Synchronously save the dataset to disk (wait to complete)
Parameters
None.
Return value
BOOL: TRUE in case of success, FALSE in case of failure. If a save is already running, this command will fail and return FALSE.
Example
$redis->save();
slaveOf
Description: Changes the slave status
Parameters
Either host (string) and port (int), or no parameter to stop being a slave.
Return value
BOOL: TRUE in case of success, FALSE in case of failure.
If successful, the time will come back as an associative array with element zero being
the unix timestamp, and element one being microseconds.
Examples
$redis->time();
slowLog
Description: Access the Redis slowLog
Parameters
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.
Return value
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
Examples
// 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');
restore - Create a key using the provided serialized value, previously obtained with dump.
get
Description: Get the value related to the specified key
Parameters
key
Return value
String or Bool: If key didn't exist, FALSE is returned. Otherwise, the value related to this key is returned.
Examples
$redis->get('key');
set
Description: Set the string value in argument as value of the key. If you're using Redis >= 2.6.12, you can pass extended options as explained below
Parameters
Key Value Timeout or Options Array (optional). If you pass an integer, phpredis will redirect to SETEX, and will try to use Redis >= 2.6.12 extended options if you pass an array with valid values
Return value
BoolTRUE if the command is successful.
Examples
// Simple key -> value set$redis->set('key', 'value');
// Will redirect, and actually make an SETEX call$redis->set('key','value', 10);
// Will set the key, if it doesn't exist, with a ttl of 10 seconds$redis->set('key', 'value', ['nx', 'ex'=>10]);
// Will set a key, if it does exist, with a ttl of 1000 milliseconds$redis->set('key', 'value', ['xx', 'px'=>1000]);
setEx, pSetEx
Description: Set the string value in argument as value of the key, with a time to live. PSETEX uses a TTL in milliseconds.
An array of keys, or an undefined number of parameters, each a key: key1key2key3 ... keyN
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.
Return value
Long Number of keys deleted.
Examples
$redis->set('key1', 'val1');
$redis->set('key2', 'val2');
$redis->set('key3', 'val3');
$redis->set('key4', 'val4');
$redis->del('key1', 'key2'); /* return 2 */$redis->del(['key3', 'key4']); /* return 2 *//* If using Redis >= 4.0.0 you can call unlink */$redis->unlink('key1', 'key2');
$redis->unlink(['key1', 'key2']);
Note:delete is an alias for del and will be removed in future versions of phpredis.
Note: This function took a single argument and returned TRUE or FALSE in phpredis versions < 4.0.0.
incr, incrBy
Description: Increment the number stored at key by one. If the second argument is filled, it will be used as the integer value of the increment.
Parameters
key value: value that will be added to key (only for incrBy)
Return value
INT the new value
Examples
$redis->incr('key1'); /* key1 didn't exists, set to 0 before the increment *//* and now has the value 1 */$redis->incr('key1'); /* 2 */$redis->incr('key1'); /* 3 */$redis->incr('key1'); /* 4 */// Will redirect, and actually make an INCRBY call$redis->incr('key1', 10); /* 14 */$redis->incrBy('key1', 10); /* 24 */
incrByFloat
Description: Increment the key with floating point precision.
Parameters
key value: (float) value that will be added to the key
Return value
FLOAT the new value
Examples
$redis->incrByFloat('key1', 1.5); /* key1 didn't exist, so it will now be 1.5 */$redis->incrByFloat('key1', 1.5); /* 3 */$redis->incrByFloat('key1', -1.5); /* 1.5 */$redis->incrByFloat('key1', 2.5); /* 4 */
decr, decrBy
Description: Decrement the number stored at key by one. If the second argument is filled, it will be used as the integer value of the decrement.
Parameters
key value: value that will be subtracted to key (only for decrBy)
Return value
INT the new value
Examples
$redis->decr('key1'); /* key1 didn't exists, set to 0 before the increment *//* and now has the value -1 */$redis->decr('key1'); /* -2 */$redis->decr('key1'); /* -3 */// Will redirect, and actually make an DECRBY call$redis->decr('key1', 10); /* -13 */$redis->decrBy('key1', 10); /* -23 */
mGet, getMultiple
Description: Get the values of all the specified keys. If one or more keys don't exist, the array will contain FALSE at the position of the key.
Parameters
Array: Array containing the list of the keys
Return value
Array: Array containing the values related to keys in argument
Note:getMultiple is an alias for mGet and will be removed in future versions of phpredis.
getSet
Description: Sets a value and returns the previous entry at that key.
Parameters
Key: key
STRING: value
Return value
A string, the previous value located at this key.
Example
$redis->set('x', '42');
$exValue = $redis->getSet('x', 'lol'); // return '42', replaces x by 'lol'$newValue = $redis->get('x')' // return 'lol'
randomKey
Description: Returns a random key.
Parameters
None.
Return value
STRING: an existing key in redis.
Example
$key = $redis->randomKey();
$surprise = $redis->get($key); // who knows what's in there.
move
Description: Moves a key to a different database.
Parameters
Key: key, the key to move.
INTEGER: dbindex, the database number to move the key to.
Return value
BOOL: TRUE in case of success, FALSE in case of failure.
Example
$redis->select(0); // switch to DB 0$redis->set('x', '42'); // write 42 to x$redis->move('x', 1); // move to DB 1$redis->select(1); // switch to DB 1$redis->get('x'); // will return 42
rename, renameKey
Description: Renames a key.
Parameters
STRING: srckey, the key to rename.
STRING: dstkey, the new name for the key.
Return value
BOOL: TRUE in case of success, FALSE in case of failure.
BOOL: TRUE if an expiration was set, and FALSE on failure or if one was not set. You can distinguish between an error and an expiration not being set by checking getLastError().
Example
$redis->set('x', '42');
$redis->expire('x', 3); // x will disappear in 3 seconds.
sleep(5); // wait 5 seconds$redis->get('x'); // will return `FALSE`, as 'x' has expired.
Note:setTimeout is an alias for expire and will be removed in future versions of phpredis.
expireAt, pexpireAt
Description: Seta specific timestamp for a key to expire in seconds or milliseconds.
BOOL: TRUE if an expiration was set and FALSE if one was not set or in the event on an error. You can detect an actual error by checking getLastError().
Example
$redis->set('x', '42');
$redis->expireAt('x', time(NULL) + 3); // x will disappear in 3 seconds.
sleep(5); // wait 5 seconds$redis->get('x'); // will return `FALSE`, as 'x' has expired.
keys, getKeys
Description: Returns the keys that match a certain pattern.
Parameters
STRING: pattern, using '*' as a wildcard.
Return value
Array of STRING: The keys that match a certain pattern.
Example
$allKeys = $redis->keys('*'); // all keys will match this.$keyWithUserPrefix = $redis->keys('user*');
Note:getKeys is an alias for keys and will be removed in future versions of phpredis.
scan
Description: Scan the keyspace for keys
Parameters
LONG (reference): Iterator, initialized to NULL
STRING, Optional: Pattern to match
LONG, Optional: Count of keys per iteration (only a suggestion to Redis)
Return value
Array, boolean: This function will return an array of keys or FALSE if Redis returned zero keys
Note: SCAN is a "directed node" command in RedisCluster
Example
/* Without enabling Redis::SCAN_RETRY (default condition) */$it = NULL;
do {
// Scan for some keys$arr_keys = $redis->scan($it);
// Redis may return empty results, so protect against thatif ($arr_keys !== FALSE) {
foreach($arr_keysas$str_key) {
echo "Here is a key: $str_key\n";
}
}
} while ($it > 0);
echo "No more keys to scan!\n";
/* With Redis::SCAN_RETRY enabled */$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
$it = NULL;
/* phpredis will retry the SCAN command if empty results are returned from the server, so no empty results check is required. */while ($arr_keys = $redis->scan($it)) {
foreach ($arr_keysas$str_key) {
echo "Here is a key: $str_key\n";
}
}
echo "No more keys to scan!\n";
object
Description: Describes the object pointed to by a key.
Parameters
The information to retrieve (string) and the key (string). Info can be one of the following:
"encoding"
"refcount"
"idletime"
Return value
STRING for "encoding", LONG for "refcount" and "idletime", FALSE if the key doesn't exist.
Example
$redis->object("encoding", "l"); // → ziplist$redis->object("refcount", "l"); // → 1$redis->object("idletime", "l"); // → 400 (in seconds, with a precision of 10 seconds).
type
Description: Returns the type of data pointed by a given key.
Parameters
Key: key
Return value
Depending on the type of the data pointed by the key, this method will return the following value:
string: Redis::REDIS_STRING
set: Redis::REDIS_SET
list: Redis::REDIS_LIST
zset: Redis::REDIS_ZSET
hash: Redis::REDIS_HASH
other: Redis::REDIS_NOT_FOUND
Example
$redis->type('key');
append
Description: Append specified string to the string stored in specified key.
Description: Dump a key out of a redis database, the value of which can later be passed into redis using the RESTORE command. The data
that comes out of DUMP is a binary representation of the key as Redis stores it.
Parameters
key string
Return value
The Redis encoded value of the key, or FALSE if the key doesn't exist
Examples
$redis->set('foo', 'bar');
$val = $redis->dump('foo'); // $val will be the Redis encoded key value
restore
Description: Restore a key from the result of a DUMP operation.
Parameters
key string. The key name ttl integer. How long the key should live (if zero, no expire will be set on the key) value string (binary). The Redis encoded key value (from DUMP)
Examples
$redis->set('foo', 'bar');
$val = $redis->dump('foo');
$redis->restore('bar', 0, $val); // The key 'bar', will now be equal to the key 'foo'
migrate
Description: Migrates a key to a different Redis instance.
Note:: Redis introduced migrating multiple keys in 3.0.6, so you must have at least
that version in order to call migrate with an array of keys.
Parameters
host string. The destination host port integer. The TCP port to connect to. key(s) string or array. destination-db integer. The target DB. timeout integer. The maximum amount of time given to this transfer. copy boolean, optional. Should we send the COPY flag to redis. replace boolean, optional. Should we send the REPLACE flag to redis
hStrLen - Get the string length of the value associated with field in the hash
hSet
Description: Adds a value to the hash stored at key.
Parameters
key hashKey value
Return value
LONG1 if value didn't exist and was added successfully, 0 if the value was already present and was replaced, FALSE if there was an error.
Example
$redis->del('h')
$redis->hSet('h', 'key1', 'hello'); /* 1, 'key1' => 'hello' in the hash at "h" */$redis->hGet('h', 'key1'); /* returns "hello" */$redis->hSet('h', 'key1', 'plop'); /* 0, value was replaced. */$redis->hGet('h', 'key1'); /* returns "plop" */
hSetNx
Description: Adds a value to the hash stored at key only if this field isn't already in the hash.
Return value
BOOLTRUE if the field was set, FALSE if it was already present.
Example
$redis->del('h')
$redis->hSetNx('h', 'key1', 'hello'); /* TRUE, 'key1' => 'hello' in the hash at "h" */$redis->hSetNx('h', 'key1', 'world'); /* FALSE, 'key1' => 'hello' in the hash at "h". No change since the field wasn't replaced. */
hGet
Description: Gets a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, FALSE is returned.
Parameters
key hashKey
Return value
STRING The value, if the command executed successfully BOOLFALSE in case of failure
hLen
Description: Returns the length of a hash, in number of items
Parameters
key
Return value
LONG the number of items in a hash, FALSE if the key doesn't exist or isn't a hash.
Description: Fills in a whole hash. Non-string values are converted to string, using the standard (string) cast. NULL values are stored as empty strings.
Parameters
key members: key → value array
Return value
BOOL
Examples
$redis->del('user:1');
$redis->hMSet('user:1', ['name' => 'Joe', 'salary' => 2000]);
$redis->hIncrBy('user:1', 'salary', 100); // Joe earns 100 more now.
hMGet
Description: Retrieve the values associated to the specified fields in the hash.
Parameters
key memberKeys Array
Return value
Array An array of elements, the values of the specified fields in the hash, with the hash keys as array keys.
rPushX - Append a value to a list, only if the list exists
blPop, brPop
Description: Is a blocking lPop(rPop) primitive. If at least one of the lists contains at least one element, the element will be popped from the head of the list and returned to the caller.
If all the list identified by the keys passed in arguments are empty, blPop will block during the specified timeout until an element is pushed to one of those lists. This element will be popped.
Parameters
ARRAY Array containing the keys of the lists INTEGER Timeout
Or STRING Key1 STRING Key2 STRING Key3
... STRING Keyn INTEGER Timeout
Return value
ARRAY ['listName', 'element']
Example
/* Non blocking feature */$redis->lPush('key1', 'A');
$redis->del('key2');
$redis->blPop('key1', 'key2', 10); /* ['key1', 'A'] *//* OR */$redis->blPop(['key1', 'key2'], 10); /* ['key1', 'A'] */$redis->brPop('key1', 'key2', 10); /* ['key1', 'A'] *//* OR */$redis->brPop(['key1', 'key2'], 10); /* ['key1', 'A'] *//* Blocking feature *//* process 1 */$redis->del('key1');
$redis->blPop('key1', 10);
/* blocking for 10 seconds *//* process 2 */$redis->lPush('key1', 'A');
/* process 1 *//* ['key1', 'A'] is returned*/
bRPopLPush
Description: A blocking version of rPopLPush, with an integral timeout in the third parameter.
Parameters
Key: srckey Key: dstkey Long: timeout
Return value
STRING The element that was moved in case of success, FALSE in case of timeout.
lIndex, lGet
Description: Return the specified element of the list stored at the specified key.
0 the first element, 1 the second ...
-1 the last element, -2 the penultimate ...
Return FALSE in case of a bad index or a key that doesn't point to a list.
Parameters
key index
Return value
String the element at this index BoolFALSE if the key identifies a non-string data type, or no value corresponds to this index in the list Key.
Note:lGet is an alias for lIndex and will be removed in future versions of phpredis.
lInsert
Description: Insert value in the list before or after the pivot value.
The parameter options specify the position of the insert (before or after).
If the list didn't exists, or the pivot didn't exists, the value is not inserted.
Parameters
key position Redis::BEFORE | Redis::AFTER pivot value
Return value
The number of the elements in the list, -1 if the pivot didn't exists.
Description: Adds one or more values to the head of a LIST. Creates the list if the key didn't exist. If the key exists and is not a list, FALSE is returned.
Prototype
$redis->lPush($key, $entry [, $entry, $entry]);
Return value
LONG The new length of the list in case of success, FALSE in case of Failure.
Description: Adds the string value to the head (left) of the list if the list exists.
Parameters
key value String, value to push in key
Return value
LONG The new length of the list in case of success, FALSE in case of Failure.
Examples
$redis->del('key1');
$redis->lPushx('key1', 'A'); // returns 0$redis->lPush('key1', 'A'); // returns 1$redis->lPushx('key1', 'B'); // returns 2$redis->lPushx('key1', 'C'); // returns 3/* key1 now points to the following list: [ 'A', 'B', 'C' ] */
lRange, lGetRange
Description: Returns the specified elements of the list stored at the specified key in the range [start, end]. start and stop are interpreted as indices:
0 the first element, 1 the second ...
-1 the last element, -2 the penultimate ...
Note:lGetRange is an alias for lRange and will be removed in future versions of phpredis.
lRem, lRemove
Description: Removes the first count occurrences of the value element from the list. If count is zero, all the matching elements are removed. If count is negative, elements are removed from tail to head.
Note: The argument order is not the same as in the Redis documentation. This difference is kept for compatibility reasons.
Parameters
key value count
Return value
LONG the number of elements to remove BOOLFALSE if the value identified by key is not a list.
Description: Pops a value from the tail of a list, and pushes it to the front of another list. Also return this value. (redis >= 1.1)
Parameters
Key: srckey Key: dstkey
Return value
STRING The element that was moved in case of success, FALSE in case of failure.
Example
$redis->del('x', 'y');
$redis->lPush('x', 'abc');
$redis->lPush('x', 'def');
$redis->lPush('y', '123');
$redis->lPush('y', '456');
// move the last of x to the front of y.
var_dump($redis->rPopLPush('x', 'y'));
var_dump($redis->lRange('x', 0, -1));
var_dump($redis->lRange('y', 0, -1));
Description: Returns the members of a set resulting from the intersection of all the sets held at the specified keys.
If just a single key is specified, then this command produces the members of this set. If one of the keys
is missing, FALSE is returned.
Parameters
key1, key2, keyN: keys identifying the different sets on which we will apply the intersection.
Return value
Array, contain the result of the intersection between those keys. If the intersection between the different sets is empty, the return value will be empty array.
The order is random and corresponds to redis' own internal representation of the set structure.
Note:sGetMembers is an alias for sMembers and will be removed in future versions of phpredis.
sMove
Description: Moves the specified member from the set at srcKey to the set at dstKey.
Parameters
srcKey dstKey member
Return value
BOOL If the operation is successful, return TRUE. If the srcKey and/or dstKey didn't exist, and/or the member didn't exist in srcKey, FALSE is returned.
Description: Removes and returns a random element from the set value at Key.
Parameters
key count: Integer, optional
Return value (without count argument)
String "popped" value BoolFALSE if set identified by key is empty or doesn't exist.
Return value (with count argument)
Array: Member(s) returned or an empty array if the set doesn't exist Bool: FALSE on error if the key is not a set
Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/$redis->sPop('key1'); /* 'member1', 'key1' => {'member3', 'member2'} */$redis->sPop('key1'); /* 'member3', 'key1' => {'member2'} *//* With count */$redis->sAdd('key2', 'member1', 'member2', 'member3');
$redis->sPop('key2', 3); /* Will return all members but in no particular order */
sRandMember
Description: Returns a random element from the set value at Key, without removing it.
Parameters
key count (Integer, optional)
Return value
If no count is provided, a random String value from the set will be returned. If a count
is provided, an array of values from the set will be returned. Read about the different
ways to use the count here: SRANDMEMBERBoolFALSE if set identified by key is empty or doesn't exist.
Example
$redis->sAdd('key1' , 'member1');
$redis->sAdd('key1' , 'member2');
$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/// No count$redis->sRandMember('key1'); /* 'member1', 'key1' => {'member3', 'member1', 'member2'} */$redis->sRandMember('key1'); /* 'member3', 'key1' => {'member3', 'member1', 'member2'} */// With a count$redis->sRandMember('key1', 3); // Will return an array with all members from the set$redis->sRandMember('key1', 2); // Will an array with 2 members of the set$redis->sRandMember('key1', -100); // Will return an array of 100 elements, picked from our set (with dups)$redis->sRandMember('empty-set', 100); // Will return an empty array$redis->sRandMember('not-a-set', 100); // Will return FALSE
sRem, sRemove
Description: Removes the specified member from the set value stored at key.
Key: The set to search iterator: LONG (reference) to the iterator as we go pattern: String, optional pattern to match against count: How many members to return at a time (Redis might return a different amount)
Return value
Array, boolean: PHPRedis will return an array of keys or FALSE when we're done iterating
Example
$it = NULL;
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); /* don't return empty results until we're done */while($arr_mems = $redis->sScan('set', $it, "*pattern*")) {
foreach($arr_memsas$str_mem) {
echo "Member: $str_mem\n";
}
}
$it = NULL;
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY); /* return after each iteration, even if empty */while(($arr_mems = $redis->sScan('set', $it, "*pattern*"))!==FALSE) {
if(count($arr_mems) > 0) {
foreach($arr_memsas$str_mem) {
echo "Member found: $str_mem\n";
}
} else {
echo "No members in this iteration, iterator value: $it\n";
}
}
Sorted sets
bzPop - Block until Redis can pop the highest or lowest scoring member from one or more ZSETs.
zAdd - Add one or more members to a sorted set or update its score if it already exists
zCard, zSize - Get the number of members in a sorted set
zCount - Count the members in a sorted set with scores within the given values
zIncrBy - Increment the score of a member in a sorted set
zinterstore, zInter - Intersect multiple sorted sets and store the resulting sorted set in a new key
zPop - Redis can pop the highest or lowest scoring member from one a ZSET.
zRange - Return a range of members in a sorted set, by index
Description: Block until Redis can pop the highest or lowest scoring members from one or more ZSETs. There are two commands (BZPOPMIN and BZPOPMAX for popping the lowest and highest scoring elements respectively.)
Prototype
$redis->bzPopMin(array $keys, int $timeout): array
$redis->bzPopMax(array $keys, int $timeout): array
$redis->bzPopMin(string $key1, string $key2, ... int $timeout): array
$redis->bzPopMax(string $key1, string $key2, ... int $timeout): array
Return value
ARRAY: Either an array with the key member and score of the highest or lowest element or an empty array if the timeout was reached without an element to pop.
Example
/* Wait up to 5 seconds to pop the *lowest* scoring member from sets `zs1` and `zs2`. */$redis->bzPopMin(['zs1', 'zs2'], 5);
$redis->bzPopMin('zs1', 'zs2', 5);
/* Wait up to 5 seconds to pop the *highest* scoring member from sets `zs1` and `zs2` */$redis->bzPopMax(['zs1', 'zs2'], 5);
$redis->bzPopMax('zs1', 'zs2', 5);
Note: Calling these functions with an array of keys or with a variable number of arguments is functionally identical.
zAdd
Description: Add one or more members to a sorted set or update its score if it already exists
Note: zSize is an alias for zCard and will be removed in future versions of phpredis.
zCount
Description: Returns the number of elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before start or end excludes it from the range. +inf and -inf are also valid limits.
Description: Increments the score of a member from a sorted set by a given amount.
Parameters
key value: (double) value that will be added to the member's score member
Return value
DOUBLE the new value
Examples
$redis->del('key');
$redis->zIncrBy('key', 2.5, 'member1'); /* key or member1 didn't exist, so member1's score is to 0 before the increment *//* and now has the value 2.5 */$redis->zIncrBy('key', 1, 'member1'); /* 3.5 */
zinterstore, zInter
Description: Creates an intersection of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument.
The third optional argument defines weights to apply to the sorted sets in input. In this case, the weights will be multiplied by the score of each element in the sorted set before applying the aggregation.
The forth argument defines the AGGREGATE option which specify how the results of the union are aggregated.
Parameters
keyOutput arrayZSetKeys arrayWeights aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zinterstore.
Note:zInter is an alias for zinterstore and will be removed in future versions of phpredis.
zPop
Description: Can pop the highest or lowest scoring members from one ZSETs. There are two commands (ZPOPMIN and ZPOPMAX for popping the lowest and highest scoring elements respectively.)
Prototype
$redis->zPopMin(string $key, int $count): array
$redis->zPopMax(string $key, int $count): array
$redis->zPopMin(string $key, int $count): array
$redis->zPopMax(string $key, int $count): array
Return value
ARRAY: Either an array with the key member and score of the highest or lowest element or an empty array if there is no element available.
Example
/* Pop the *lowest* scoring member from set `zs1`. */$redis->zPopMin('zs1', 5);
/* Pop the *highest* scoring member from set `zs1`. */$redis->zPopMax('zs1', 5);
zRange
Description: Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end].
Start and stop are interpreted as zero-based indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ...
Description: Returns the elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before start or end excludes it from the range. +inf and -inf are also valid limits. zRevRangeByScore returns the same items in reverse order, when the start and end parameters are swapped.
Parameters
key start: string end: string options: array
Two options are available: withscores => TRUE, and limit => [$offset, $count]
Description: Returns a lexicographical range of members in a sorted set, assuming the members have the same score. The min and max values are required to start with '(' (exclusive), '[' (inclusive), or be exactly the values '-' (negative inf) or '+' (positive inf). The command must be called with either three or five arguments or will return FALSE.
Parameters
key: The ZSET you wish to run against min: The minimum alphanumeric value you wish to get max: The maximum alphanumeric value you wish to get offset: Optional argument if you wish to start somewhere other than the first element. limit: Optional argument if you wish to limit the number of elements returned.
Return value
Array containing the values in the specified range.
Description: Returns the rank of a given member in the specified sorted set, starting at 0 for the item with the smallest score. zRevRank starts at 0 for the item with the largest score.
Note:zDeleteRangeByScore and zRemoveRangeByScore are an alias for zRemRangeByScore and will be removed in future versions of phpredis.
zRevRange
Description: Returns the elements of the sorted set stored at the specified key in the range [start, end] in reverse order. start and stop are interpreted as zero-based indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ...
Parameters
key start: long end: long withscores: bool = false
Description: Creates an union of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument.
The third optional argument defines weights to apply to the sorted sets in input. In this case, the weights will be multiplied by the score of each element in the sorted set before applying the aggregation.
The forth argument defines the AGGREGATE option which specify how the results of the union are aggregated.
Parameters
keyOutput arrayZSetKeys arrayWeights aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zunionstore.
Note:zUnion is an alias for zunionstore and will be removed in future versions of phpredis.
zScan
Description: Scan a sorted set for members, with optional pattern and count
Parameters
key: String, the set to scan iterator: Long (reference), initialized to NULL pattern: String (optional), the pattern to match count: How many keys to return per iteration (Redis might return a different number)
Return value
Array, boolean PHPRedis will return matching keys from Redis, or FALSE when iteration is complete
Description: Add one or more geospatial items to the specified key. This function must be called with at least one longitude, latitude, member triplet.
Return value
Integer: The number of elements added to the geospatial key.
Example
$redis->del("myplaces");
/* Since the key will be new, $result will be 2 */$result = $redis->geoAdd(
"myplaces",
-122.431, 37.773, "San Francisco",
-157.858, 21.315, "Honolulu"
);
Description: Return members of a set with geospatial information that are within the radius specified by the caller.
Options Array
The georadius command can be called with various options that control how Redis returns results. The following table describes the options phpredis supports. All options are case insensitive.
Key
Value
Description
COUNT
integer > 0
Limit how many results are returned
WITHCOORD
Return longitude and latitude of matching members
WITHDIST
Return the distance from the center
WITHHASH
Return the raw geohash-encoded score
ASC
Sort results in ascending order
DESC
Sort results in descending order
STORE
key
Store results in key
STOREDIST
key
Store the results as distances in key
Note: It doesn't make sense to pass both ASC and DESC options but if both are passed the last one passed will be used. Note: When using STORE[DIST] in Redis Cluster, the store key must has to the same slot as the query key or you will get a CROSSLOT error.
Return value
Mixed: When no STORE option is passed, this function returns an array of results. If it is passed this function returns the number of stored entries.
Example
/* Add some cities */$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
echo "Within 300 miles of Honolulu:\n";
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi'));
echo "\nWithin 300 miles of Honolulu with distances:\n";
$options = ['WITHDIST'];
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options));
echo "\nFirst result within 300 miles of Honolulu with distances:\n";
$options['count'] = 1;
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options));
echo "\nFirst result within 300 miles of Honolulu with distances in descending sort order:\n";
$options[] = 'DESC';
var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options));
Output
Within 300 miles of Honolulu:
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(4) "Maui"
}
Within 300 miles of Honolulu with distances:
array(2) {
[0]=>
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(6) "0.0002"
}
[1]=>
array(2) {
[0]=>
string(4) "Maui"
[1]=>
string(8) "104.5615"
}
}
First result within 300 miles of Honolulu with distances:
array(1) {
[0]=>
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(6) "0.0002"
}
}
First result within 300 miles of Honolulu with distances in descending sort order:
array(1) {
[0]=>
array(2) {
[0]=>
string(4) "Maui"
[1]=>
string(8) "104.5615"
}
}
Description: This method is identical to geoRadius except that instead of passing a longitude and latitude as the "source" you pass an existing member in the geospatial set.
Array: The zero or more entries that are close enough to the member given the distance and radius specified.
Example
$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui");
echo "Within 300 miles of Honolulu:\n";
var_dump($redis->geoRadiusByMember("hawaii", "Honolulu", 300, 'mi'));
echo "\nFirst match within 300 miles of Honolulu:\n";
var_dump($redis->geoRadiusByMember("hawaii", "Honolulu", 300, 'mi', ['count' => 1]));
Output
Within 300 miles of Honolulu:
array(2) {
[0]=>
string(8) "Honolulu"
[1]=>
string(4) "Maui"
}
First match within 300 miles of Honolulu:
array(1) {
[0]=>
string(8) "Honolulu"
}
$obj_redis->xAdd('mystream', "*", ['field' => 'value']);
$obj_redis->xAdd('mystream', "*", ['field' => 'value'], 1000); // set max length of stream to 1000$obj_redis->xAdd('mystream', "*", ['field' => 'value'], 1000, true); // set max length of stream to ~1000
Description: Claim ownership of one or more pending messages.
Options Array
$options = [
/* Note: 'TIME', and 'IDLE' are mutually exclusive */'IDLE' => $value, /* Set the idle time to $value ms */,
'TIME' => $value, /* Set the idle time to now - $value */'RETRYCOUNT' => $value, /* Update message retrycount to $value */'FORCE', /* Claim the message(s) even if they're not pending anywhere */'JUSTID', /* Instruct Redis to only return IDs */
];
Return value
Array: Either an array of message IDs along with corresponding data, or just an array of IDs (if the 'JUSTID' option was passed).
Description: Get a range of messages from a given stream.
Return value
Array: The messages in the stream within the requested range.
Example
/* Get everything in this stream */$obj_redis->xRange('mystream', '-', '+');
/* Only the first two messages */$obj_redis->xRange('mystream', '-', '+', 2);
Description: This method is similar to xRead except that it supports reading messages for a specific consumer group.
Return value
Array: The messages delivered to this consumer group (if any).
Examples
/* Consume messages for 'mygroup', 'consumer1' */$obj_redis->xReadGroup('mygroup', 'consumer1', ['s1' => 0, 's2' => 0]);
/* Consume messages for 'mygroup', 'consumer1' which were not consumed yet by the group */$obj_redis->xReadGroup('mygroup', 'consumer1', ['s1' => '>', 's2' => '>']);
/* Read a single message as 'consumer2' wait for up to a second until a message arrives. */$obj_redis->xReadGroup('mygroup', 'consumer2', ['s1' => 0, 's2' => 0], 1, 1000);
Description: Trim the stream length to a given maximum. If the "approximate" flag is pasesed, Redis will use your size as a hint but only trim trees in whole nodes (this is more efficient).
Return value
long: The number of messages trimmed from the stream.
Example
/* Trim to exactly 100 messages */$obj_redis->xTrim('mystream', 100);
/* Let Redis approximate the trimming */$obj_redis->xTrim('mystream', 100, true);
patterns: An array of patterns to match callback: Either a string or an array with an object and method. The callback will get four arguments ($redis, $pattern, $channel, $message) return value: Mixed. Any non-null return value in the callback will be returned to the caller.
Description: Subscribe to channels. Warning: this function will probably change in the future.
Parameters
channels: an array of channels to subscribe to callback: either a string or an Array($instance, 'method_name'). The callback function receives 3 parameters: the redis instance, the channel name, and the message.
return value: Mixed. Any non-null return value in the callback will be returned to the caller.
Description: A command allowing you to get information on the Redis pub/sub system.
Parameters
keyword: String, which can be: "channels", "numsub", or "numpat" argument: Optional, variant. For the "channels" subcommand, you can pass a string pattern. For "numsub" an array of channel names.
Return value
CHANNELS: Returns an array where the members are the matching channels. NUMSUB: Returns a key/value array where the keys are channel names and values are their counts. NUMPAT: Integer return containing the number active pattern subscriptions
Example
$redis->pubSub("channels"); /*All channels */$redis->pubSub("channels", "*pattern*"); /* Just channels matching your pattern */$redis->pubSub("numsub", ["chan1", "chan2"]); /*Get subscriber counts for 'chan1' and 'chan2'*/$redis->pubSub("numpat"); /* Get the number of pattern subscribers */
Generic
rawCommand - Execute any generic command against the server.
rawCommand
Description: A method to execute any arbitrary command against the a Redis server
Parameters
This method is variadic and takes a dynamic number of arguments of various types (string, long, double), but must be passed at least one argument (the command keyword itself).
Return value
The return value can be various types depending on what the server itself returns. No post processing is done to the returned value and must be handled by the client code.
watch, unwatch - Watches a key for modifications by another client.
multi, exec, discard.
Description: Enter and exit transactional mode.
Parameters
(optional) Redis::MULTI or Redis::PIPELINE. Defaults to Redis::MULTI. A Redis::MULTI block of commands runs as a single transaction; a Redis::PIPELINE block is simply transmitted faster to the server, but without any guarantee of atomicity. discard cancels a transaction.
Return value
multi() returns the Redis instance and enters multi-mode. Once in multi-mode, all subsequent method calls return the same object until exec() is called.
Description: Watches a key for modifications by another client.
If the key is modified between WATCH and EXEC, the MULTI/EXEC transaction will fail (return FALSE). unwatch cancels all the watching of all keys by this client.
Parameters
keys: string for one key or array for a list of keys
Example
$redis->watch('x'); // or for a list of keys: $redis->watch(['x','another key']);/* long code here during the execution of which other clients could well modify `x` */$ret = $redis->multi()
->incr('x')
->exec();
/*$ret = FALSE if x has been modified between the call to WATCH and the call to EXEC.*/
Mixed. What is returned depends on what the LUA script itself returns, which could be a scalar value (int/string), or an array.
Arrays that are returned can also contain other arrays, if that's how it was set up in your LUA script. If there is an error
executing the LUA script, the getLastError() function can tell you the message that came back from Redis (e.g. compile error).
Description: Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself.
In order to run this command Redis will have to have already loaded the script,
either by running it or via the SCRIPT LOAD command.
Parameters
script_sha string. The sha1 encoded hash of the script you want to run. args array, optional. Arguments to pass to the LUA script. num_keys int, optional. The number of arguments that should go into the KEYS array, vs. the ARGV array when Redis spins the script
SCRIPT LOAD will return the SHA1 hash of the passed script on success, and FALSE on failure.
SCRIPT FLUSH should always return TRUE
SCRIPT KILL will return true if a script was able to be killed and false if not
SCRIPT EXISTS will return an array with TRUE or FALSE for each passed script
client
Description: Issue the CLIENT command with various arguments.
The Redis CLIENT command can be used in four ways.
CLIENT LIST
CLIENT GETNAME
CLIENT SETNAME [name]
CLIENT KILL [ip:port]
Usage
$redis->client('list'); // Get a list of clients$redis->client('getname'); // Get the name of the current connection$redis->client('setname', 'somename'); // Set the name of the current connection$redis->client('kill', <ip:port>); // Kill the process at ip:port
Return value
This will vary depending on which client command was executed.
CLIENT LIST will return an array of arrays with client information.
CLIENT GETNAME will return the client name or false if none has been set
CLIENT SETNAME will return true if it can be set and false if not
CLIENT KILL will return true if the client can be killed, and false if not
Note: phpredis will attempt to reconnect so you can actually kill your own connection
but may not notice losing it!
getLastError
Description: The last error message (if any)
Parameters
none
Return value
A string with the last returned script based error message, or NULL if there is no error
Examples
$redis->eval('this-is-not-lua');
$err = $redis->getLastError();
// "ERR Error compiling script (new function): user_script:1: '=' expected near '-'"
clearLastError
Description: Clear the last error message
Parameters
none
Return value
BOOL TRUE
Examples
$redis->set('x', 'a');
$redis->incr('x');
$err = $redis->getLastError();
// "ERR value is not an integer or out of range"$redis->clearLastError();
$err = $redis->getLastError();
// NULL
_prefix
Description: A utility method to prefix the value with the prefix setting for phpredis.
Parameters
value string. The value you wish to prefix
Return value
If a prefix is set up, the value now prefixed. If there is no prefix, the value will be returned unchanged.
Examples
$redis->setOption(Redis::OPT_PREFIX, 'my-prefix:');
$redis->_prefix('my-value'); // Will return 'my-prefix:my-value'
_serialize
Description: A utility method to serialize values manually.
This method allows you to serialize a value with whatever serializer is configured, manually.
This can be useful for serialization/unserialization of data going in and out of EVAL commands
as phpredis can't automatically do this itself. Note that if no serializer is set, phpredis
will change Array values to 'Array', and Objects to 'Object'.
Description: A utility method to unserialize data with whatever serializer is set up.
If there is no serializer set, the value will be returned unchanged. If there is a serializer set up,
and the data passed in is malformed, an exception will be thrown. This can be useful if phpredis is
serializing values, and you return something from redis in a LUA script that is serialized.
Parameters
value string. The value to be unserialized
Examples
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
$redis->_unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // Will return [1,2,3]
Introspection
isConnected
Description: A method to determine if a phpredis object thinks it's connected to a server
Parameters
None
Return value
Boolean Returns TRUE if phpredis thinks it's connected and FALSE if not
getHost
Description: Retrieve our host or unix socket that we're connected to
Parameters
None
Return value
Mixed The host or unix socket we're connected to or FALSE if we're not connected
getPort
Description: Get the port we're connected to
Parameters
None
Return value
Mixed Returns the port we're connected to or FALSE if we're not connected
getDbNum
Description: Get the database number phpredis is pointed to
Parameters
None
Return value
Mixed Returns the database number (LONG) phpredis thinks it's pointing to or FALSE if we're not connected
getTimeout
Description: Get the (write) timeout in use for phpredis
Parameters
None
Return value
Mixed The timeout (DOUBLE) specified in our connect call or FALSE if we're not connected
getReadTimeout
Description: Get the read timeout specified to phpredis or FALSE if we're not connected
Parameters
None
Return value
Mixed Returns the read timeout (which can be set using setOption and Redis::OPT_READ_TIMEOUT) or FALSE if we're not connected
getPersistentID
Description: Gets the persistent ID that phpredis is using
Parameters
None
Return value
Mixed Returns the persistent id phpredis is using (which will only be set if connected with pconnect), NULL if we're not
using a persistent ID, and FALSE if we're not connected
getAuth
Description: Get the password (or username and password if using Redis 6 ACLs) used to authenticate the connection.
Parameters
None
Return value
Mixed Returns NULL if no username/password are set, the password string if a password is set, and a [username, password] array if authenticated with a username and password.
phpredis/phpredis
PhpRedis
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 [email protected] (Twitter, Mastodon), [email protected] (@yatsukhnenko), or [email protected] (@yowgi).
API Documentation
These are a work in progress, but will eventually replace our ONE README TO RULE THEM ALL docs.
Supporting the project
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
Sponsors
Table of contents
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
andsession.save_path
in your php.ini to tell phpredis where to store the sessions:session.save_path
can have a simplehost:port
format too, but you need to provide thetcp://
scheme if you want to use the parameters. The following parameters are available: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 supportingEX
andNX
options ofSET
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"
.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.
Following INI variables can be used to configure session locking:
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:
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.
Classes and methods
Usage
Class Redis
Description: Creates a Redis client
Example
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
command.Example
Parameters
host: string. can be a host, or the path to a unix domain socket.
port: int (default is 6379, should be -1 for unix domain socket)
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 value is string then it used as persistend id, else value casts to boolean
auth: mixed, authentication information
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
@TODO: OPT_SERIALIZER, AFTER, BEFORE,...
Connection
connect, open
Description: Connects to a Redis instance.
Parameters
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 it will use default_socket_timeout)
reserved: should be '' if retry_interval is specified
retry_interval: int, value in milliseconds (optional)
read_timeout: float, value in seconds (optional, default is 0 meaning it will use default_socket_timeout)
others: array, with PhpRedis >= 5.3.0, it allows setting auth and stream configuration.
Return value
BOOL:
TRUE
on success,FALSE
on error.Example
Note:
open
is an alias forconnect
and will be removed in future versions of phpredis.pconnect, popen
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
andpopen
then working like their non persistent equivalents.Parameters
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 it will use default_socket_timeout)
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 it will use default_socket_timeout)
Return value
BOOL:
TRUE
on success,FALSE
on error.Example
Note:
popen
is an alias forpconnect
and will be removed in future versions of phpredis.auth
Description: Authenticate the connection using a password or a username and password. Warning: The password is sent in plain-text over the network.
Parameters
MIXED: password
Return value
BOOL:
TRUE
if the connection is authenticated,FALSE
otherwise.Note: In order to authenticate with a username and password you need Redis >= 6.0.
Example
select
Description: Change the selected database for the current connection.
Parameters
INTEGER: dbindex, the database number to switch to.
Return value
TRUE
in case of success,FALSE
in case of failure.Example
See method for example: move
swapdb
Description: Swap one Redis database with another atomically
Parameters
INTEGER: db1
INTEGER: db2
Return value
TRUE
on success andFALSE
on failure.Note: Requires Redis >= 4.0.0
Example
close
Description: Disconnects from the Redis instance.
Note: Closing a persistent connection requires PhpRedis >= 4.2.0.
Parameters
None.
Return value
BOOL:
TRUE
on success,FALSE
on failure.setOption
Description: Set client option.
Parameters
parameter name
parameter value
Return value
BOOL:
TRUE
on success,FALSE
on error.Example
getOption
Description: Get client option.
Parameters
parameter name
Return value
Parameter value.
Example
ping
Description: Check the current connection status.
Prototype
Return value
Mixed: This method returns
TRUE
on success, or the passed string if called with an argument.Example
Note: Prior to PhpRedis 5.0.0 this command simply returned the string
+PONG
.echo
Description: Sends a string to Redis, which replies with the same string
Parameters
STRING: The message to send.
Return value
STRING: the same message.
Retry and backoff
Maximum retries
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.Example
Backoff algorithms
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:Redis::BACKOFF_ALGORITHM_DEFAULT
Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER
Redis::BACKOFF_ALGORITHM_FULL_JITTER
Redis::BACKOFF_ALGORITHM_EQUAL_JITTER
Redis::BACKOFF_ALGORITHM_EXPONENTIAL
Redis::BACKOFF_ALGORITHM_UNIFORM
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
andRedis::OPT_BACKOFF_CAP
options, respectively.Example
Server
acl
Description: Execute the Redis ACL command.
Parameters
variable: Minumum of one argument for
Redis
and two forRedisCluster
.Example
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 usedel
. The Redis unlink command is non-blocking and will perform the actual deletion asynchronously.bgRewriteAOF
Description: Start the background rewrite of AOF (Append-Only File)
Parameters
None.
Return value
BOOL:
TRUE
in case of success,FALSE
in case of failure.Example
bgSave
Description: Asynchronously save the dataset to disk (in background)
Parameters
None.
Return value
BOOL:
TRUE
in case of success,FALSE
in case of failure. If a save is already running, this command will fail and returnFALSE
.Example
config
Description: Get or Set the Redis server configuration parameters.
Prototype
Return value
Associative array for
GET
, key(s) -> value(s)bool for
SET
,RESETSTAT
, andREWRITE
Examples
dbSize
Description: Return the number of keys in selected database.
Parameters
None.
Return value
INTEGER: DB size, in number of keys.
Example
flushAll
Description: Remove all keys from all databases.
Parameters
async (bool) requires server version 4.0.0 or greater
Return value
BOOL: Always
TRUE
.Example
flushDb
Description: Remove all keys from the current database.
Prototype
Return value
BOOL: This command returns true on success and false on failure.
Example
info
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:
You can pass a variety of options to INFO (per the Redis documentation), which will modify what is returned.
Parameters
option: The option to provide redis (e.g. "COMMANDSTATS", "CPU")
Example
lastSave
Description: Returns the timestamp of the last disk save.
Parameters
None.
Return value
INT: timestamp.
Example
save
Description: Synchronously save the dataset to disk (wait to complete)
Parameters
None.
Return value
BOOL:
TRUE
in case of success,FALSE
in case of failure. If a save is already running, this command will fail and returnFALSE
.Example
slaveOf
Description: Changes the slave status
Parameters
Either host (string) and port (int), or no parameter to stop being a slave.
Return value
BOOL:
TRUE
in case of success,FALSE
in case of failure.Example
time
Description: Return the current server time.
Parameters
(none)
Return value
If successful, the time will come back as an associative array with element zero being the unix timestamp, and element one being microseconds.
Examples
slowLog
Description: Access the Redis slowLog
Parameters
Operation (string): This can be either
GET
,LEN
, orRESET
Length (integer), optional: If executing a
SLOWLOG GET
command, you can pass an optional length.Return value
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
Examples
Keys and Strings
Strings
Keys
get
Description: Get the value related to the specified key
Parameters
key
Return value
String or Bool: If key didn't exist,
FALSE
is returned. Otherwise, the value related to this key is returned.Examples
set
Description: Set the string value in argument as value of the key. If you're using Redis >= 2.6.12, you can pass extended options as explained below
Parameters
Key
Value
Timeout or Options Array (optional). If you pass an integer, phpredis will redirect to SETEX, and will try to use Redis >= 2.6.12 extended options if you pass an array with valid values
Return value
Bool
TRUE
if the command is successful.Examples
setEx, pSetEx
Description: Set the string value in argument as value of the key, with a time to live. PSETEX uses a TTL in milliseconds.
Parameters
Key TTL Value
Return value
Bool
TRUE
if the command is successful.Examples
setNx
Description: Set the string value in argument as value of the key if the key doesn't already exist in the database.
Parameters
key value
Return value
Bool
TRUE
in case of success,FALSE
in case of failure.Examples
del, delete, unlink
Description: Remove specified keys.
Parameters
An array of keys, or an undefined number of parameters, each a key: key1 key2 key3 ... keyN
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 usedel
. The Redis unlink command is non-blocking and will perform the actual deletion asynchronously.Return value
Long Number of keys deleted.
Examples
Note:
delete
is an alias fordel
and will be removed in future versions of phpredis.exists
Description: Verify if the specified key exists.
Parameters
key
Return value
long: The number of keys tested that do exist.
Examples
Note: This function took a single argument and returned TRUE or FALSE in phpredis versions < 4.0.0.
incr, incrBy
Description: Increment the number stored at key by one. If the second argument is filled, it will be used as the integer value of the increment.
Parameters
key
value: value that will be added to key (only for incrBy)
Return value
INT the new value
Examples
incrByFloat
Description: Increment the key with floating point precision.
Parameters
key
value: (float) value that will be added to the key
Return value
FLOAT the new value
Examples
decr, decrBy
Description: Decrement the number stored at key by one. If the second argument is filled, it will be used as the integer value of the decrement.
Parameters
key
value: value that will be subtracted to key (only for decrBy)
Return value
INT the new value
Examples
mGet, getMultiple
Description: Get the values of all the specified keys. If one or more keys don't exist, the array will contain
FALSE
at the position of the key.Parameters
Array: Array containing the list of the keys
Return value
Array: Array containing the values related to keys in argument
Examples
Note:
getMultiple
is an alias formGet
and will be removed in future versions of phpredis.getSet
Description: Sets a value and returns the previous entry at that key.
Parameters
Key: key
STRING: value
Return value
A string, the previous value located at this key.
Example
randomKey
Description: Returns a random key.
Parameters
None.
Return value
STRING: an existing key in redis.
Example
move
Description: Moves a key to a different database.
Parameters
Key: key, the key to move.
INTEGER: dbindex, the database number to move the key to.
Return value
BOOL:
TRUE
in case of success,FALSE
in case of failure.Example
rename, renameKey
Description: Renames a key.
Parameters
STRING: srckey, the key to rename.
STRING: dstkey, the new name for the key.
Return value
BOOL:
TRUE
in case of success,FALSE
in case of failure.Example
Note:
renameKey
is an alias forrename
and will be removed in future versions of phpredis.renameNx
Description: Same as rename, but will not replace a key if the destination already exists. This is the same behaviour as setNx.
expire, pexpire
Description: Sets an expiration on a key in either seconds or milliseconds.
Prototype
Return value
BOOL:
TRUE
if an expiration was set, andFALSE
on failure or if one was not set. You can distinguish between an error and an expiration not being set by checkinggetLastError()
.Example
Note:
setTimeout
is an alias forexpire
and will be removed in future versions of phpredis.expireAt, pexpireAt
Description: Seta specific timestamp for a key to expire in seconds or milliseconds.
Prototype
Return value
BOOL:
TRUE
if an expiration was set andFALSE
if one was not set or in the event on an error. You can detect an actual error by checkinggetLastError()
.Example
keys, getKeys
Description: Returns the keys that match a certain pattern.
Parameters
STRING: pattern, using '*' as a wildcard.
Return value
Array of STRING: The keys that match a certain pattern.
Example
Note:
getKeys
is an alias forkeys
and will be removed in future versions of phpredis.scan
Description: Scan the keyspace for keys
Parameters
LONG (reference): Iterator, initialized to NULL STRING, Optional: Pattern to match LONG, Optional: Count of keys per iteration (only a suggestion to Redis)
Return value
Array, boolean: This function will return an array of keys or FALSE if Redis returned zero keys
Note: SCAN is a "directed node" command in RedisCluster
Example
object
Description: Describes the object pointed to by a key.
Parameters
The information to retrieve (string) and the key (string). Info can be one of the following:
Return value
STRING for "encoding", LONG for "refcount" and "idletime",
FALSE
if the key doesn't exist.Example
type
Description: Returns the type of data pointed by a given key.
Parameters
Key: key
Return value
Depending on the type of the data pointed by the key, this method will return the following value:
string: Redis::REDIS_STRING
set: Redis::REDIS_SET
list: Redis::REDIS_LIST
zset: Redis::REDIS_ZSET
hash: Redis::REDIS_HASH
other: Redis::REDIS_NOT_FOUND
Example
append
Description: Append specified string to the string stored in specified key.
Parameters
Key Value
Return value
INTEGER: Size of the value after the append
Example
getRange
Description: Return a substring of a larger string
Parameters
key
start
end
Return value
STRING: the substring
Example
Note:
substr
is an alias forgetRange
and will be removed in future versions of phpredis.setRange
Description: Changes a substring of a larger string.
Parameters
key offset value
Return value
STRING: the length of the string after it was modified.
Example
strLen
Description: Get the length of a string value.
Parameters
key
Return value
INTEGER
Example
getBit
Description: Return a single bit out of a larger string
Parameters
key
offset
Return value
LONG: the bit value (0 or 1)
Example
setBit
Description: Changes a single bit of a string.
Parameters
key
offset
value: bool or int (1 or 0)
Return value
LONG: 0 or 1, the value of the bit before it was set.
Example
bitOp
Description: Bitwise operation on multiple keys.
Parameters
operation: either "AND", "OR", "NOT", "XOR"
ret_key: return key
key1
key2...
Return value
LONG: The size of the string stored in the destination key.
bitCount
Description: Count bits in a string.
Parameters
key
Return value
LONG: The number of bits set to 1 in the value behind the input key.
sort
Description: Sort the elements in a list, set or sorted set.
Parameters
Key: key Options: [key => value, ...] - optional, with the following keys and values:
Return value
An array of values, or a number corresponding to the number of elements stored if that was used.
Example
ttl, pttl
Description: Returns the time to live left for a given key in seconds (ttl), or milliseconds (pttl).
Parameters
Key: key
Return value
LONG: The time to live in seconds. If the key has no ttl,
-1
will be returned, and-2
if the key doesn't exist.Example
persist
Description: Remove the expiration timer from a key.
Parameters
Key: key
Return value
BOOL:
TRUE
if a timeout was removed,FALSE
if the key didn’t exist or didn’t have an expiration timer.Example
mSet, mSetNx
Description: Sets multiple key-value pairs in one atomic command. MSETNX only returns TRUE if all the keys were set (see SETNX).
Parameters
Pairs: [key => value, ...]
Return value
Bool
TRUE
in case of success,FALSE
in case of failure.Example
Output:
dump
Description: Dump a key out of a redis database, the value of which can later be passed into redis using the RESTORE command. The data that comes out of DUMP is a binary representation of the key as Redis stores it.
Parameters
key string
Return value
The Redis encoded value of the key, or FALSE if the key doesn't exist
Examples
restore
Description: Restore a key from the result of a DUMP operation.
Parameters
key string. The key name
ttl integer. How long the key should live (if zero, no expire will be set on the key)
value string (binary). The Redis encoded key value (from DUMP)
Examples
migrate
Description: Migrates a key to a different Redis instance.
Note:: Redis introduced migrating multiple keys in 3.0.6, so you must have at least that version in order to call
migrate
with an array of keys.Parameters
host string. The destination host
port integer. The TCP port to connect to.
key(s) string or array.
destination-db integer. The target DB.
timeout integer. The maximum amount of time given to this transfer.
copy boolean, optional. Should we send the COPY flag to redis.
replace boolean, optional. Should we send the REPLACE flag to redis
Examples
Hashes
hSet
Description: Adds a value to the hash stored at key.
Parameters
key
hashKey
value
Return value
LONG
1
if value didn't exist and was added successfully,0
if the value was already present and was replaced,FALSE
if there was an error.Example
hSetNx
Description: Adds a value to the hash stored at key only if this field isn't already in the hash.
Return value
BOOL
TRUE
if the field was set,FALSE
if it was already present.Example
hGet
Description: Gets a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist,
FALSE
is returned.Parameters
key
hashKey
Return value
STRING The value, if the command executed successfully
BOOL
FALSE
in case of failurehLen
Description: Returns the length of a hash, in number of items
Parameters
key
Return value
LONG the number of items in a hash,
FALSE
if the key doesn't exist or isn't a hash.Example
hDel
Description: Removes a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist,
FALSE
is returned.Parameters
key
hashKey1
hashKey2
...
Return value
LONG the number of deleted keys, 0 if the key doesn't exist,
FALSE
if the key isn't a hash.hKeys
Description: Returns the keys in a hash, as an array of strings.
Parameters
Key: key
Return value
An array of elements, the keys of the hash. This works like PHP's array_keys().
Example
Output:
The order is random and corresponds to redis' own internal representation of the set structure.
hVals
Description: Returns the values in a hash, as an array of strings.
Parameters
Key: key
Return value
An array of elements, the values of the hash. This works like PHP's array_values().
Example
Output:
The order is random and corresponds to redis' own internal representation of the set structure.
hGetAll
Description: Returns the whole hash, as an array of strings indexed by strings.
Parameters
Key: key
Return value
An array of elements, the contents of the hash.
Example
Output:
The order is random and corresponds to redis' own internal representation of the set structure.
hExists
Description: Verify if the specified member exists in a key.
Parameters
key
memberKey
Return value
BOOL: If the member exists in the hash table, return
TRUE
, otherwise returnFALSE
.Examples
hIncrBy
Description: Increments the value of a member from a hash by a given amount.
Parameters
key
member
value: (integer) value that will be added to the member's value
Return value
LONG the new value
Examples
hIncrByFloat
Description: Increments the value of a hash member by the provided float value
Parameters
key
member
value: (float) value that will be added to the member's value
Return value
FLOAT the new value
Examples
hMSet
Description: Fills in a whole hash. Non-string values are converted to string, using the standard
(string)
cast. NULL values are stored as empty strings.Parameters
key
members: key → value array
Return value
BOOL
Examples
hMGet
Description: Retrieve the values associated to the specified fields in the hash.
Parameters
key
memberKeys Array
Return value
Array An array of elements, the values of the specified fields in the hash, with the hash keys as array keys.
Examples
hScan
Description: Scan a HASH value for members, with an optional pattern and count
Parameters
key: String
iterator: Long (reference)
pattern: Optional pattern to match against
count: How many keys to return in a go (only a suggestion to Redis)
Return value
Array An array of members that match our pattern
Examples
hStrLen
Description: Get the string length of the value associated with field in the hash stored at key.
Parameters
key: String
field: String
Return value
LONG the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all.
Lists
blPop, brPop
Description: Is a blocking lPop(rPop) primitive. If at least one of the lists contains at least one element, the element will be popped from the head of the list and returned to the caller. If all the list identified by the keys passed in arguments are empty, blPop will block during the specified timeout until an element is pushed to one of those lists. This element will be popped.
Parameters
ARRAY Array containing the keys of the lists
INTEGER Timeout
Or
STRING Key1
STRING Key2
STRING Key3
...
STRING Keyn
INTEGER Timeout
Return value
ARRAY ['listName', 'element']
Example
bRPopLPush
Description: A blocking version of
rPopLPush
, with an integral timeout in the third parameter.Parameters
Key: srckey
Key: dstkey
Long: timeout
Return value
STRING The element that was moved in case of success,
FALSE
in case of timeout.lIndex, lGet
Description: Return the specified element of the list stored at the specified key.
0 the first element, 1 the second ...
-1 the last element, -2 the penultimate ...
Return
FALSE
in case of a bad index or a key that doesn't point to a list.Parameters
key
index
Return value
String the element at this index
Bool
FALSE
if the key identifies a non-string data type, or no value corresponds to this index in the listKey
.Example
Note:
lGet
is an alias forlIndex
and will be removed in future versions of phpredis.lInsert
Description: Insert value in the list before or after the pivot value.
The parameter options specify the position of the insert (before or after). If the list didn't exists, or the pivot didn't exists, the value is not inserted.
Parameters
key
position Redis::BEFORE | Redis::AFTER
pivot
value
Return value
The number of the elements in the list, -1 if the pivot didn't exists.
Example
lPop
Description: Return and remove the first element of the list.
Parameters
key
Return value
STRING if command executed successfully
BOOL
FALSE
in case of failure (empty list)Example
lPush
Description: Adds one or more values to the head of a LIST. Creates the list if the key didn't exist. If the key exists and is not a list,
FALSE
is returned.Prototype
Return value
LONG The new length of the list in case of success,
FALSE
in case of Failure.Examples
lPushx
Description: Adds the string value to the head (left) of the list if the list exists.
Parameters
key
value String, value to push in key
Return value
LONG The new length of the list in case of success,
FALSE
in case of Failure.Examples
lRange, lGetRange
Description: Returns the specified elements of the list stored at the specified key in the range [start, end]. start and stop are interpreted as indices:
0 the first element, 1 the second ...
-1 the last element, -2 the penultimate ...
Parameters
key
start
end
Return value
Array containing the values in specified range.
Example
Note:
lGetRange
is an alias forlRange
and will be removed in future versions of phpredis.lRem, lRemove
Description: Removes the first
count
occurrences of the value element from the list. If count is zero, all the matching elements are removed. If count is negative, elements are removed from tail to head.Note: The argument order is not the same as in the Redis documentation. This difference is kept for compatibility reasons.
Parameters
key
value
count
Return value
LONG the number of elements to remove
BOOL
FALSE
if the value identified by key is not a list.Example
Note:
lRemove
is an alias forlRem
and will be removed in future versions of phpredis.lSet
Description: Set the list at index with the new value.
Parameters
key
index
value
Return value
BOOL
TRUE
if the new value was set.FALSE
if the index is out of range, or data type identified by key is not a list.Example
lTrim, listTrim
Description: Trims an existing list so that it will contain only a specified range of elements.
Parameters
key
start
stop
Return value
Array
Bool return
FALSE
if the key identify a non-list value.Example
Note:
listTrim
is an alias forlTrim
and will be removed in future versions of phpredis.rPop
Description: Returns and removes the last element of the list.
Parameters
key
Return value
STRING if command executed successfully
BOOL
FALSE
in case of failure (empty list)Example
rPopLPush
Description: Pops a value from the tail of a list, and pushes it to the front of another list. Also return this value. (redis >= 1.1)
Parameters
Key: srckey
Key: dstkey
Return value
STRING The element that was moved in case of success,
FALSE
in case of failure.Example
Output:
rPush
Description: Adds one or more entries to the tail of a LIST. Redis will create the list if it doesn't exist.
Prototype
Return value
LONG The new length of the list in case of success,
FALSE
in case of Failure.Examples
rPushX
Description: Adds the string value to the tail (right) of the list if the list exists.
FALSE
in case of Failure.Parameters
key
value String, value to push in key
Return value
LONG The new length of the list in case of success,
FALSE
in case of Failure.Examples
lLen, lSize
Description: Returns the size of a list identified by Key.
If the list didn't exist or is empty, the command returns 0. If the data type identified by Key is not a list, the command return
FALSE
.Parameters
Key
Return value
LONG The size of the list identified by Key exists.
BOOL
FALSE
if the data type identified by Key is not listExample
Note:
lSize
is an alias forlLen
and will be removed in future versions of phpredis.Sets
sAdd
Description: Adds a value to the set value stored at key.
Parameters
key
value
Return value
LONG the number of elements added to the set.
Example
sCard, sSize
Description: Returns the cardinality of the set identified by key.
Parameters
key
Return value
LONG the cardinality of the set identified by key, 0 if the set doesn't exist.
Example
Note:
sSize
is an alias forsCard
and will be removed in future versions of phpredis.sDiff
Description: Performs the difference between N sets and returns it.
Parameters
Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.
Return value
Array of strings: The difference of the first set will all the others.
Example
Return value: all elements of s0 that are neither in s1 nor in s2.
sDiffStore
Description: Performs the same action as sDiff, but stores the result in the first key
Parameters
Key: dstkey, the key to store the diff into.
Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis
Return value
INTEGER: The cardinality of the resulting set, or
FALSE
in case of a missing key.Example
Return value: the number of elements of s0 that are neither in s1 nor in s2.
sInter
Description: Returns the members of a set resulting from the intersection of all the sets held at the specified keys.
If just a single key is specified, then this command produces the members of this set. If one of the keys is missing,
FALSE
is returned.Parameters
key1, key2, keyN: keys identifying the different sets on which we will apply the intersection.
Return value
Array, contain the result of the intersection between those keys. If the intersection between the different sets is empty, the return value will be empty array.
Examples
Output:
sInterStore
Description: Performs a sInter command and stores the result in a new set.
Parameters
Key: dstkey, the key to store the diff into.
Keys: key1, key2... keyN. key1..keyN are intersected as in sInter.
Return value
INTEGER: The cardinality of the resulting set, or
FALSE
in case of a missing key.Example
Output:
sIsMember, sContains
Description: Checks if
value
is a member of the set stored at the keykey
.Parameters
key
value
Return value
BOOL
TRUE
ifvalue
is a member of the set at keykey
,FALSE
otherwise.Example
Note:
sContains
is an alias forsIsMember
and will be removed in future versions of phpredis.sMembers, sGetMembers
Description: Returns the contents of a set.
Parameters
Key: key
Return value
An array of elements, the contents of the set.
Example
Output:
The order is random and corresponds to redis' own internal representation of the set structure.
Note:
sGetMembers
is an alias forsMembers
and will be removed in future versions of phpredis.sMove
Description: Moves the specified member from the set at srcKey to the set at dstKey.
Parameters
srcKey
dstKey
member
Return value
BOOL If the operation is successful, return
TRUE
. If the srcKey and/or dstKey didn't exist, and/or the member didn't exist in srcKey,FALSE
is returned.Example
sPop
Description: Removes and returns a random element from the set value at Key.
Parameters
key
count: Integer, optional
Return value (without count argument)
String "popped" value
Bool
FALSE
if set identified by key is empty or doesn't exist.Return value (with count argument)
Array: Member(s) returned or an empty array if the set doesn't exist
Bool:
FALSE
on error if the key is not a setExample
sRandMember
Description: Returns a random element from the set value at Key, without removing it.
Parameters
key
count (Integer, optional)
Return value
If no count is provided, a random String value from the set will be returned. If a count is provided, an array of values from the set will be returned. Read about the different ways to use the count here: SRANDMEMBER Bool
FALSE
if set identified by key is empty or doesn't exist.Example
sRem, sRemove
Description: Removes the specified member from the set value stored at key.
Parameters
key
member
Return value
LONG The number of elements removed from the set.
Example
Note:
sRemove
is an alias forsRem
and will be removed in future versions of phpredis.sUnion
Description: Performs the union between N sets and returns it.
Parameters
Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.
Return value
Array of strings: The union of all these sets.
Note:
sUnion
can also take a single array with keys (see example below).Example
Return value: all elements that are either in s0 or in s1 or in s2.
sUnionStore
Description: Performs the same action as sUnion, but stores the result in the first key
Parameters
Key: dstkey, the key to store the diff into.
Keys: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis.
Return value
INTEGER: The cardinality of the resulting set, or
FALSE
in case of a missing key.Example
Return value: the number of elements that are either in s0 or in s1 or in s2.
sScan
Description: Scan a set for members
Parameters
Key: The set to search
iterator: LONG (reference) to the iterator as we go
pattern: String, optional pattern to match against
count: How many members to return at a time (Redis might return a different amount)
Return value
Array, boolean: PHPRedis will return an array of keys or FALSE when we're done iterating
Example
Sorted sets
bzPop
Description: Block until Redis can pop the highest or lowest scoring members from one or more ZSETs. There are two commands (
BZPOPMIN
andBZPOPMAX
for popping the lowest and highest scoring elements respectively.)Prototype
Return value
ARRAY: Either an array with the key member and score of the highest or lowest element or an empty array if the timeout was reached without an element to pop.
Example
Note: Calling these functions with an array of keys or with a variable number of arguments is functionally identical.
zAdd
Description: Add one or more members to a sorted set or update its score if it already exists
Prototype
Parameters
key: string options: array (optional) score: double
value: string score1: double value1: string
Return value
Long 1 if the element is added. 0 otherwise.
Example
zCard, zSize
Description: Returns the cardinality of an ordered set.
Parameters
key
Return value
Long, the set's cardinality
Example
Note:
zSize
is an alias forzCard
and will be removed in future versions of phpredis.zCount
Description: Returns the number of elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before
start
orend
excludes it from the range. +inf and -inf are also valid limits.Parameters
key
start: string
end: string
Return value
LONG the size of a corresponding zRangeByScore.
Example
zIncrBy
Description: Increments the score of a member from a sorted set by a given amount.
Parameters
key
value: (double) value that will be added to the member's score
member
Return value
DOUBLE the new value
Examples
zinterstore, zInter
Description: Creates an intersection of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument.
The third optional argument defines
weights
to apply to the sorted sets in input. In this case, theweights
will be multiplied by the score of each element in the sorted set before applying the aggregation. The forth argument defines theAGGREGATE
option which specify how the results of the union are aggregated.Parameters
keyOutput
arrayZSetKeys
arrayWeights
aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zinterstore.
Return value
LONG The number of values in the new sorted set.
Example
Note:
zInter
is an alias forzinterstore
and will be removed in future versions of phpredis.zPop
Description: Can pop the highest or lowest scoring members from one ZSETs. There are two commands (
ZPOPMIN
andZPOPMAX
for popping the lowest and highest scoring elements respectively.)Prototype
Return value
ARRAY: Either an array with the key member and score of the highest or lowest element or an empty array if there is no element available.
Example
zRange
Description: Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end].
Start and stop are interpreted as zero-based indices:
0
the first element,1
the second ...-1
the last element,-2
the penultimate ...Parameters
key start: long
end: long
withscores: bool = false
Return value
Array containing the values in specified range.
Example
zRangeByScore, zRevRangeByScore
Description: Returns the elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before
start
orend
excludes it from the range. +inf and -inf are also valid limits. zRevRangeByScore returns the same items in reverse order, when thestart
andend
parameters are swapped.Parameters
key
start: string
end: string
options: array
Two options are available:
withscores => TRUE
, andlimit => [$offset, $count]
Return value
Array containing the values in specified range.
Example
zRangeByLex
Description: Returns a lexicographical range of members in a sorted set, assuming the members have the same score. The min and max values are required to start with '(' (exclusive), '[' (inclusive), or be exactly the values '-' (negative inf) or '+' (positive inf). The command must be called with either three or five arguments or will return FALSE.
Parameters
key: The ZSET you wish to run against
min: The minimum alphanumeric value you wish to get
max: The maximum alphanumeric value you wish to get
offset: Optional argument if you wish to start somewhere other than the first element.
limit: Optional argument if you wish to limit the number of elements returned.
Return value
Array containing the values in the specified range.
Example
zRank, zRevRank
Description: Returns the rank of a given member in the specified sorted set, starting at 0 for the item with the smallest score. zRevRank starts at 0 for the item with the largest score.
Parameters
key
member
Return value
Long, the item's rank.
Example
zRem, zDelete, zRemove
Description: Delete one or more members from a sorted set.
Prototype
Return value
LONG: The number of members deleted.
Example
Note:
zDelete
andzRemove
are an alias forzRem
and will be removed in future versions of phpredis.zRemRangeByRank, zDeleteRangeByRank
Description: Deletes the elements of the sorted set stored at the specified key which have rank in the range [start,end].
Parameters
key
start: LONG
end: LONG
Return value
LONG The number of values deleted from the sorted set
Example
Note:
zDeleteRangeByRank
is an alias forzRemRangeByRank
and will be removed in future versions of phpredis.zRemRangeByScore, zDeleteRangeByScore, zRemoveRangeByScore
Description: Deletes the elements of the sorted set stored at the specified key which have scores in the range [start,end].
Parameters
key
start: double or "+inf" or "-inf" string
end: double or "+inf" or "-inf" string
Return value
LONG The number of values deleted from the sorted set
Example
Note:
zDeleteRangeByScore
andzRemoveRangeByScore
are an alias forzRemRangeByScore
and will be removed in future versions of phpredis.zRevRange
Description: Returns the elements of the sorted set stored at the specified key in the range [start, end] in reverse order. start and stop are interpreted as zero-based indices:
0
the first element,1
the second ...-1
the last element,-2
the penultimate ...Parameters
key
start: long
end: long
withscores: bool = false
Return value
Array containing the values in specified range.
Example
zScore
Description: Returns the score of a given member in the specified sorted set.
Parameters
key
member
Return value
Double or FALSE when the value is not found
Example
zunionstore, zUnion
Description: Creates an union of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument.
The third optional argument defines
weights
to apply to the sorted sets in input. In this case, theweights
will be multiplied by the score of each element in the sorted set before applying the aggregation. The forth argument defines theAGGREGATE
option which specify how the results of the union are aggregated.Parameters
keyOutput
arrayZSetKeys
arrayWeights
aggregateFunction Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zunionstore.
Return value
LONG The number of values in the new sorted set.
Example
Note:
zUnion
is an alias forzunionstore
and will be removed in future versions of phpredis.zScan
Description: Scan a sorted set for members, with optional pattern and count
Parameters
key: String, the set to scan
iterator: Long (reference), initialized to NULL
pattern: String (optional), the pattern to match
count: How many keys to return per iteration (Redis might return a different number)
Return value
Array, boolean PHPRedis will return matching keys from Redis, or FALSE when iteration is complete
Example
HyperLogLogs
pfAdd
Description: Adds the specified elements to the specified HyperLogLog.
Prototype
Parameters
Key
Array of values
Return value
Integer: 1 if at least 1 HyperLogLog internal register was altered. 0 otherwise.
Example
pfCount
Description: Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
Prototype
Parameters
Key or Array of keys
Return value
Integer: The approximated number of unique elements observed via pfAdd.
Example
pfMerge
Description: Merge N different HyperLogLogs into a single one.
Prototype
Parameters
Destination Key
Array of Source Keys
Return value
BOOL:
TRUE
on success,FALSE
on error.Example
Geocoding
geoAdd
Prototype
Description: Add one or more geospatial items to the specified key. This function must be called with at least one longitude, latitude, member triplet.
Return value
Integer: The number of elements added to the geospatial key.
Example
geoHash
Prototype
Description: Retrieve Geohash strings for one or more elements of a geospatial index.
Return value
Array: One or more Redis Geohash encoded strings.
Example
Output
geoPos
Prototype
Description: Return longitude, latitude positions for each requested member.
Return value
Array: One or more longitude/latitude positions
Example
Output
GeoDist
Prototype
Description: Return the distance between two members in a geospatial set. If units are passed it must be one of the following values:
Return value
Double: The distance between the two passed members in the units requested (meters by default).
Example
Output
geoRadius
Prototype
Description: Return members of a set with geospatial information that are within the radius specified by the caller.
Options Array
The georadius command can be called with various options that control how Redis returns results. The following table describes the options phpredis supports. All options are case insensitive.
Note: It doesn't make sense to pass both
ASC
andDESC
options but if both are passed the last one passed will be used.Note: When using
STORE[DIST]
in Redis Cluster, the store key must has to the same slot as the query key or you will get aCROSSLOT
error.Return value
Mixed: When no
STORE
option is passed, this function returns an array of results. If it is passed this function returns the number of stored entries.Example
Output
geoRadiusByMember
Prototype
Description: This method is identical to geoRadius except that instead of passing a longitude and latitude as the "source" you pass an existing member in the geospatial set.
Options Array
See geoRadius command for options array.
Return value
Array: The zero or more entries that are close enough to the member given the distance and radius specified.
Example
Output
Streams
xAck
Prototype
Description: Acknowledge one or more messages on behalf of a consumer group.
Return value
long: The number of messages Redis reports as acknowledged.
Example
xAdd
Prototype
Description: Add a message to a stream
Return value
String: The added message ID
Example
xClaim
Prototype
Description: Claim ownership of one or more pending messages.
Options Array
Return value
Array: Either an array of message IDs along with corresponding data, or just an array of IDs (if the 'JUSTID' option was passed).
Example
xDel
Prototype
Description: Delete one or more messages from a stream.
Return value
long: The number of messages removed
Example
xGroup
Prototype
Description: This command is used in order to create, destroy, or manage consumer groups.
Return value
Mixed: This command returns different types depending on the specific XGROUP command executed.
Example
xInfo
Prototype
Description: Get information about a stream or consumer groups.
Return value
Mixed: This command returns different types depending on which subcommand is used.
Example
xLen
Prototype
Description: Get the length of a given stream
Return value
Long: The number of messages in the stream.
Example
xPending
Prototype
Description: Get information about pending messages in a given stream.
Return value
Array: Information about the pending messages, in various forms depending on the specific invocation of XPENDING.
Examples
xRange
Prototype
Description: Get a range of messages from a given stream.
Return value
Array: The messages in the stream within the requested range.
Example
xRead
Prototype
Description: Read data from one or more streams and only return IDs greater than sent in the command.
Return value
Array: The messages in the stream newer than the IDs passed to Redis (if any).
Example
xReadGroup
Prototype
Description: This method is similar to xRead except that it supports reading messages for a specific consumer group.
Return value
Array: The messages delivered to this consumer group (if any).
Examples
xRevRange
Prototype
Description: This is identical to xRange except the results come back in reverse order. Also note that Redis reverses the order of "start" and "end".
Return value
Array: The messages in the range specified.
Example
xTrim
Prototype
Description: Trim the stream length to a given maximum. If the "approximate" flag is pasesed, Redis will use your size as a hint but only trim trees in whole nodes (this is more efficient).
Return value
long: The number of messages trimmed from the stream.
Example
Pub/sub
pSubscribe
Description: Subscribe to channels by pattern
Parameters
patterns: An array of patterns to match
callback: Either a string or an array with an object and method. The callback will get four arguments ($redis, $pattern, $channel, $message)
return value: Mixed. Any non-null return value in the callback will be returned to the caller.
Example
publish
Description: Publish messages to channels. Warning: this function will probably change in the future.
Parameters
channel: a channel to publish to
message: string
Example
subscribe
Description: Subscribe to channels. Warning: this function will probably change in the future.
Parameters
channels: an array of channels to subscribe to
callback: either a string or an Array($instance, 'method_name'). The callback function receives 3 parameters: the redis instance, the channel name, and the message. return value: Mixed. Any non-null return value in the callback will be returned to the caller.
Example
pubSub
Description: A command allowing you to get information on the Redis pub/sub system.
Parameters
keyword: String, which can be: "channels", "numsub", or "numpat"
argument: Optional, variant. For the "channels" subcommand, you can pass a string pattern. For "numsub" an array of channel names.
Return value
CHANNELS: Returns an array where the members are the matching channels.
NUMSUB: Returns a key/value array where the keys are channel names and values are their counts.
NUMPAT: Integer return containing the number active pattern subscriptions
Example
Generic
rawCommand
Description: A method to execute any arbitrary command against the a Redis server
Parameters
This method is variadic and takes a dynamic number of arguments of various types (string, long, double), but must be passed at least one argument (the command keyword itself).
Return value
The return value can be various types depending on what the server itself returns. No post processing is done to the returned value and must be handled by the client code.
Example
Transactions
multi, exec, discard.
Description: Enter and exit transactional mode.
Parameters
(optional)
Redis::MULTI
orRedis::PIPELINE
. Defaults toRedis::MULTI
. ARedis::MULTI
block of commands runs as a single transaction; aRedis::PIPELINE
block is simply transmitted faster to the server, but without any guarantee of atomicity.discard
cancels a transaction.Return value
multi()
returns the Redis instance and enters multi-mode. Once in multi-mode, all subsequent method calls return the same object untilexec()
is called.Example
watch, unwatch
Description: Watches a key for modifications by another client.
If the key is modified between
WATCH
andEXEC
, the MULTI/EXEC transaction will fail (returnFALSE
).unwatch
cancels all the watching of all keys by this client.Parameters
keys: string for one key or array for a list of keys
Example
Scripting
eval
Description: Evaluate a LUA script serverside
Parameters
script string.
args array, optional.
num_keys int, optional.
Return value
Mixed. What is returned depends on what the LUA script itself returns, which could be a scalar value (int/string), or an array. Arrays that are returned can also contain other arrays, if that's how it was set up in your LUA script. If there is an error executing the LUA script, the getLastError() function can tell you the message that came back from Redis (e.g. compile error).
Examples
evalSha
Description: Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself.
In order to run this command Redis will have to have already loaded the script, either by running it or via the SCRIPT LOAD command.
Parameters
script_sha string. The sha1 encoded hash of the script you want to run.
args array, optional. Arguments to pass to the LUA script.
num_keys int, optional. The number of arguments that should go into the KEYS array, vs. the ARGV array when Redis spins the script
Return value
Mixed. See EVAL
Examples
script
Description: Execute the Redis SCRIPT command to perform various operations on the scripting subsystem.
Usage
Return value
client
Description: Issue the CLIENT command with various arguments.
The Redis CLIENT command can be used in four ways.
Usage
Return value
This will vary depending on which client command was executed.
Note: phpredis will attempt to reconnect so you can actually kill your own connection but may not notice losing it!
getLastError
Description: The last error message (if any)
Parameters
none
Return value
A string with the last returned script based error message, or NULL if there is no error
Examples
clearLastError
Description: Clear the last error message
Parameters
none
Return value
BOOL TRUE
Examples
_prefix
Description: A utility method to prefix the value with the prefix setting for phpredis.
Parameters
value string. The value you wish to prefix
Return value
If a prefix is set up, the value now prefixed. If there is no prefix, the value will be returned unchanged.
Examples
_serialize
Description: A utility method to serialize values manually.
This method allows you to serialize a value with whatever serializer is configured, manually. This can be useful for serialization/unserialization of data going in and out of EVAL commands as phpredis can't automatically do this itself. Note that if no serializer is set, phpredis will change Array values to 'Array', and Objects to 'Object'.
Parameters
value: Mixed. The value to be serialized
Examples
_unserialize
Description: A utility method to unserialize data with whatever serializer is set up.
If there is no serializer set, the value will be returned unchanged. If there is a serializer set up, and the data passed in is malformed, an exception will be thrown. This can be useful if phpredis is serializing values, and you return something from redis in a LUA script that is serialized.
Parameters
value string. The value to be unserialized
Examples
Introspection
isConnected
Description: A method to determine if a phpredis object thinks it's connected to a server
Parameters
None
Return value
Boolean Returns TRUE if phpredis thinks it's connected and FALSE if not
getHost
Description: Retrieve our host or unix socket that we're connected to
Parameters
None
Return value
Mixed The host or unix socket we're connected to or FALSE if we're not connected
getPort
Description: Get the port we're connected to
Parameters
None
Return value
Mixed Returns the port we're connected to or FALSE if we're not connected
getDbNum
Description: Get the database number phpredis is pointed to
Parameters
None
Return value
Mixed Returns the database number (LONG) phpredis thinks it's pointing to or FALSE if we're not connected
getTimeout
Description: Get the (write) timeout in use for phpredis
Parameters
None
Return value
Mixed The timeout (DOUBLE) specified in our connect call or FALSE if we're not connected
getReadTimeout
Description: Get the read timeout specified to phpredis or FALSE if we're not connected
Parameters
None
Return value
Mixed Returns the read timeout (which can be set using setOption and Redis::OPT_READ_TIMEOUT) or FALSE if we're not connected
getPersistentID
Description: Gets the persistent ID that phpredis is using
Parameters
None
Return value
Mixed Returns the persistent id phpredis is using (which will only be set if connected with pconnect), NULL if we're not using a persistent ID, and FALSE if we're not connected
getAuth
Description: Get the password (or username and password if using Redis 6 ACLs) used to authenticate the connection.
Parameters
None
Return value
Mixed Returns NULL if no username/password are set, the password string if a password is set, and a
[username, password]
array if authenticated with a username and password.