This extension provides an API for communicating with Redis database, a persistent key-value database with built-in net interface written in ANSI-C for Posix systems.
It is a fork of alfonsojimenez's phpredis, adding many methods and fixing a lot of issues.
This code is maintained by Owlient. You can send comments, patches, questions here on github or to:
phpize ./configure make && make install
You can generate a debian package for PHP5, accessible from Apache 2 by running ./mkdeb-apache2.sh
or with dpkg-buildpackage
or svn-buildpackage
.
This extension exports a single class, Redis
(and RedisException
used in case of errors).
If the install fails on OSX, type the following commands in your shell before trying again:
MACOSX_DEPLOYMENT_TARGET=10.6 CFLAGS="-arch i386 -arch x86_64 -g -Os -pipe -no-cpp-precomp" CCFLAGS="-arch i386 -arch x86_64 -g -Os -pipe" CXXFLAGS="-arch i386 -arch x86_64 -g -Os -pipe" LDFLAGS="-arch i386 -arch x86_64 -bind_at_load" export CFLAGS CXXFLAGS LDFLAGS CCFLAGS MACOSX_DEPLOYMENT_TARGET
phpredis can be used to store PHP sessions. To do this, configure session.save_handler
and session.save_path
in your php.ini to tell phpredis where to store the sessions:
session.save_handler = redis session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2"
session.save_path
can have a simple host:port
format too, but you need to provide the tcp://
scheme if you want to use the parameters. The following parameters are available:
- weight (integer): the weight of a host is used in comparison with the others in order to customize the session distribution on several hosts. If host A has twice the weight of host B, it will get twice the amount of sessions. In the example, host1 stores 20% of all the sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/1+2+2). The target host is determined once and for all at the start of the session, and doesn't change. The default weight is 1.
- timeout (float): the connection timeout to a redis host, expressed in seconds. If the host is unreachable in that amount of time, the session storage will be unavailable for the client. The default timeout is very high (86400 seconds).
- persistent (integer, should be 1 or 0): defines if a persistent connection should be used. (experimental setting)
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 with the SETEX
command (at least 2.0).
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
.
Creates a Redis client
$redis = new Redis();
Connects to a Redis instance.
host: string. can be a host, or the path to a unix domain socket
port: int, optional
timeout: float, value in seconds (optional, default is 0 meaning unlimited)
BOOL: TRUE
on success, FALSE
on error.
$redis->connect('127.0.0.1', 6379); $redis->connect('127.0.0.1'); // port 6379 by default $redis->connect('127.0.0.1', 6379, 2.5); // 2.5 sec timeout. $redis->connect('/tmp/redis.sock'); // unix domain socket.
Connects to a Redis instance or reuse a connection already established with pconnect
/popen
.
The connection will not be closed on close
or end of request until the php process ends.
So be patient on to many open FD's (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.
This feature is not available in threaded versions. pconnect
and popen
then working like their non
persistent equivalents.
host: string. can be a host, or the path to a unix domain socket
port: int, optional
timeout: float, value in seconds (optional, default is 0 meaning unlimited)
persistent_id: string. identity for the requested persistent connection
BOOL: TRUE
on success, FALSE
on error.
$redis->pconnect('127.0.0.1', 6379); $redis->pconnect('127.0.0.1'); // port 6379 by default - same connection like before. $redis->pconnect('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 the the three before. $redis->pconnect('/tmp/redis.sock'); // unix domain socket - would be another connection than the four before.
Disconnects from the Redis instance, except when pconnect
is used.
Set client option.
parameter name
parameter value
BOOL: TRUE
on success, FALSE
on error.
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // don't serialize data $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // use built-in serialize/unserialize $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // use igBinary serialize/unserialize $redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys
Get client option.
parameter name
Parameter value.
$redis->getOption(Redis::OPT_SERIALIZER); // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY.
Check the current connection status
(none)
STRING: +PONG
on success. Throws a RedisException object on connectivity error, as described above.
Get the value related to the specified key
key
String or Bool: If key didn't exist, FALSE
is returned. Otherwise, the value related to this key is returned.
$redis->get('key');
Set the string value in argument as value of the key.
Key
Value
Timeout (optional). Calling SETEX
is preferred if you want a timeout.
Bool TRUE
if the command is successful.
$redis->set('key', 'value');
Set the string value in argument as value of the key, with a time to live.
Key TTL Value
Bool TRUE
if the command is successful.
$redis->setex('key', 3600, 'value'); // sets key → value, with 1h TTL.
Set the string value in argument as value of the key if the key doesn't already exist in the database.
key value
Bool TRUE
in case of success, FALSE
in case of failure.
$redis->setnx('key', 'value'); /* return TRUE */ $redis->setnx('key', 'value'); /* return FALSE */
Remove specified keys.
An array of keys, or an undefined number of parameters, each a key: key1 key2 key3 ... keyN
Long Number of keys deleted.
$redis->set('key1', 'val1'); $redis->set('key2', 'val2'); $redis->set('key3', 'val3'); $redis->set('key4', 'val4'); $redis->delete('key1', 'key2'); /* return 2 */ $redis->delete(array('key3', 'key4')); /* return 2 */
Enter and exit transactional mode.
(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.
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.
$ret = $redis->multi() ->set('key1', 'val1') ->get('key1') ->set('key2', 'val2') ->get('key2') ->exec(); /* $ret == array( 0 => TRUE, 1 => 'val1', 2 => TRUE, 3 => 'val2'); */
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.
keys: a list of keys
$redis->watch('x'); /* 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. */
Subscribe to channels. Warning: this function will probably change in the future.
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.
function f($redis, $chan, $msg) { switch($chan) { case 'chan-1': ... break; case 'chan-2': ... break; case 'chan-2': ... break; } } $redis->subscribe(array('chan-1', 'chan-2', 'chan-3'), 'f'); // subscribe to 3 chans
Publish messages to channels. Warning: this function will probably change in the future.
channel: a channel to publish to
messsage: string
$redis->publish('chan-1', 'hello, world!'); // send message.
Verify if the specified key exists.
key
BOOL: If the key exists, return TRUE
, otherwise return FALSE
.
$redis->set('key', 'value'); $redis->exists('key'); /* TRUE */ $redis->exists('NonExistingKey'); /* FALSE */
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.
key
value: value that will be added to key (only for incrBy)
INT the new value
$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 */ $redis->incrBy('key1', 10); /* 14 */
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.
key
value: value that will be substracted to key (only for decrBy)
INT the new value
$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 */ $redis->decrBy('key1', 10); /* -13 */
Get the values of all the specified keys. If one or more keys dont exist, the array will contain FALSE
at the position of the key.
Array: Array containing the list of the keys
Array: Array containing the values related to keys in argument
$redis->set('key1', 'value1'); $redis->set('key2', 'value2'); $redis->set('key3', 'value3'); $redis->getMultiple(array('key1', 'key2', 'key3')); /* array('value1', 'value2', 'value3'); $redis->getMultiple(array('key0', 'key1', 'key5')); /* array(`FALSE`, 'value2', `FALSE`);
Adds the string value to the head (left) of the list. Creates the list if the key didn't exist. If the key exists and is not a list, FALSE
is returned.
key
value String, value to push in key
LONG The new length of the list in case of success, FALSE
in case of Failure.
$redis->delete('key1'); $redis->lPush('key1', 'C'); // returns 1 $redis->lPush('key1', 'B'); // returns 2 $redis->lPush('key1', 'A'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */
Adds the string value to the tail (right) of the list. Creates the list if the key didn't exist. If the key exists and is not a list, FALSE
is returned.
key
value String, value to push in key
LONG The new length of the list in case of success, FALSE
in case of Failure.
$redis->delete('key1'); $redis->rPush('key1', 'A'); // returns 1 $redis->rPush('key1', 'B'); // returns 2 $redis->rPush('key1', 'C'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */
Adds the string value to the head (left) of the list if the list exists.
key
value String, value to push in key
LONG The new length of the list in case of success, FALSE
in case of Failure.
$redis->delete('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' ] */
Adds the string value to the tail (right) of the list if the ist exists. FALSE
in case of Failure.
key
value String, value to push in key
LONG The new length of the list in case of success, FALSE
in case of Failure.
$redis->delete('key1'); $redis->rPushx('key1', 'A'); // returns 0 $redis->rPush('key1', 'A'); // returns 1 $redis->rPushx('key1', 'B'); // returns 2 $redis->rPushx('key1', 'C'); // returns 3 /* key1 now points to the following list: [ 'A', 'B', 'C' ] */
Return and remove the first element of the list.
key
STRING if command executed successfully
BOOL FALSE
in case of failure (empty list)
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lPop('key1'); /* key1 => [ 'B', 'C' ] */
Returns and removes the first element of the list.
key
STRING if command executed successfully
BOOL FALSE
in case of failure (empty list)
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->rPop('key1'); /* key1 => [ 'A', 'B' ] */
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. Il 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.
ARRAY Array containing the keys of the lists INTEGER Timeout Or STRING Key1 STRING Key2 STRING Key3 ... STRING Keyn INTEGER Timeout
ARRAY array('listName', 'element')
/* Non blocking feature */ $redis->lPush('key1', 'A'); $redis->delete('key2'); $redis->blPop('key1', 'key2', 10); /* array('key1', 'A') */ /* OR */ $redis->blPop(array('key1', 'key2'), 10); /* array('key1', 'A') */ $redis->brPop('key1', 'key2', 10); /* array('key1', 'A') */ /* OR */ $redis->brPop(array('key1', 'key2'), 10); /* array('key1', 'A') */ /* Blocking feature */ /* process 1 */ $redis->delete('key1'); $redis->blPop('key1', 10); /* blocking for 10 seconds */ /* process 2 */ $redis->lPush('key1', 'A'); /* process 1 */ /* array('key1', 'A') is returned*/
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
.
Key
LONG The size of the list identified by Key exists.
BOOL FALSE
if the data type identified by Key is not list
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lSize('key1');/* 3 */ $redis->rPop('key1'); $redis->lSize('key1');/* 2 */
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.
key index
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 list Key
.
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lGet('key1', 0); /* 'A' */ $redis->lGet('key1', -1); /* 'C' */ $redis->lGet('key1', 10); /* `FALSE` */
Set the list at index with the new value.
key index value
BOOL TRUE
if the new value is setted. FALSE
if the index is out of range, or data type identified by key is not a list.
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ $redis->lGet('key1', 0); /* 'A' */ $redis->lSet('key1', 0, 'X'); $redis->lGet('key1', 0); /* 'X' */
Returns the specified elements of the list stored at the specified key in the range [start, end]. start and stop are interpretated as indices: 0 the first element, 1 the second ... -1 the last element, -2 the penultimate ...
key start end
Array containing the values in specified range.
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); $redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */
Trims an existing list so that it will contain only a specified range of elements.
key start stop
Array
Bool return FALSE
if the key identify a non-list value.
$redis->rPush('key1', 'A'); $redis->rPush('key1', 'B'); $redis->rPush('key1', 'C'); $redis->lRange('key1', 0, -1); /* array('A', 'B', 'C') */ $redis->lTrim('key1', 0, 1); $redis->lRange('key1', 0, -1); /* array('A', 'B') */
Removes the first count
occurences 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.
key
value
count
LONG the number of elements to remove
BOOL FALSE
if the value identified by key is not a list.
$redis->lPush('key1', 'A'); $redis->lPush('key1', 'B'); $redis->lPush('key1', 'C'); $redis->lPush('key1', 'A'); $redis->lPush('key1', 'A'); $redis->lRange('key1', 0, -1); /* array('A', 'A', 'C', 'B', 'A') */ $redis->lRem('key1', 'A', 2); /* 2 */ $redis->lRange('key1', 0, -1); /* array('C', 'B', 'A') */
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.
key position Redis::BEFORE | Redis::AFTER pivot value
The number of the elements in the list, -1 if the pivot didn't exists.
$redis->delete('key1'); $redis->lInsert('key1', Redis::AFTER, 'A', 'X'); /* 0 */ $redis->lPush('key1', 'A'); $redis->lPush('key1', 'B'); $redis->lPush('key1', 'C'); $redis->lInsert('key1', Redis::BEFORE, 'C', 'X'); /* 4 */ $redis->lRange('key1', 0, -1); /* array('A', 'B', 'X', 'C') */ $redis->lInsert('key1', Redis::AFTER, 'C', 'Y'); /* 5 */ $redis->lRange('key1', 0, -1); /* array('A', 'B', 'X', 'C', 'Y') */ $redis->lInsert('key1', Redis::AFTER, 'W', 'value'); /* -1 */
Adds a value to the set value stored at key. If this value is already in the set, FALSE
is returned.
key value
BOOL TRUE
if value didn't exist and was added successfully, FALSE
if the value is already present.
$redis->sAdd('key1' , 'set1'); /* TRUE, 'key1' => {'set1'} */ $redis->sAdd('key1' , 'set2'); /* TRUE, 'key1' => {'set1', 'set2'}*/ $redis->sAdd('key1' , 'set2'); /* FALSE, 'key1' => {'set1', 'set2'}*/
Removes the specified member from the set value stored at key.
key member
BOOL TRUE
if the member was present in the set, FALSE
if it didn't.
$redis->sAdd('key1' , 'set1'); $redis->sAdd('key1' , 'set2'); $redis->sAdd('key1' , 'set3'); /* 'key1' => {'set1', 'set2', 'set3'}*/ $redis->sRem('key1', 'set2'); /* 'key1' => {'set1', 'set3'} */
Moves the specified member from the set at srcKey to the set at dstKey.
srcKey dstKey member
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.
$redis->sAdd('key1' , 'set11'); $redis->sAdd('key1' , 'set12'); $redis->sAdd('key1' , 'set13'); /* 'key1' => {'set11', 'set12', 'set13'}*/ $redis->sAdd('key2' , 'set21'); $redis->sAdd('key2' , 'set22'); /* 'key2' => {'set21', 'set22'}*/ $redis->sMove('key1', 'key2', 'set13'); /* 'key1' => {'set11', 'set12'} */ /* 'key2' => {'set21', 'set22', 'set13'} */
Checks if value
is a member of the set stored at the key key
.
key value
BOOL TRUE
if value
is a member of the set at key key
, FALSE
otherwise.
$redis->sAdd('key1' , 'set1'); $redis->sAdd('key1' , 'set2'); $redis->sAdd('key1' , 'set3'); /* 'key1' => {'set1', 'set2', 'set3'}*/ $redis->sIsMember('key1', 'set1'); /* TRUE */ $redis->sIsMember('key1', 'setX'); /* FALSE */
Returns the cardinality of the set identified by key.
key
LONG the cardinality of the set identified by key, 0 if the set doesn't exist.
$redis->sAdd('key1' , 'set1'); $redis->sAdd('key1' , 'set2'); $redis->sAdd('key1' , 'set3'); /* 'key1' => {'set1', 'set2', 'set3'}*/ $redis->sCard('key1'); /* 3 */ $redis->sCard('keyX'); /* 0 */
Removes and returns a random element from the set value at Key.
key
String "popped" value
Bool FALSE
if set identified by key is empty or doesn't exist.