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 or to n.favrefelix@gmail.com (@yowgi).
Everything you should need to install PhpRedis on your system.
phpize
./configure [--enable-redis-igbinary]
make && make install
If you would like phpredis to serialize your data using the igbinary library, run configure with --enable-redis-igbinary
.
make install
copies redis.so
to an appropriate location, but you still need to enable the module in the PHP config file. To do so, either edit your php.ini or add a redis.ini file in /etc/php5/conf.d
with the following contents: extension=redis.so
.
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). Check out https://github.com/ukko/phpredis-phpdoc for a PHP stub that you can use in your IDE for code completion.
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
If that still fails and you are running Zend Server CE, try this right before "make": ./configure CFLAGS="-arch i386"
.
Taken from Compiling phpredis on Zend Server CE/OSX .
See also: Install Redis & PHP Extension PHPRedis with Macports.
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)
- 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, empty by default): 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 with the SETEX
command (at least 2.0).
phpredis can also connect to a unix domain socket: session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0
.
See instructions from @char101 on how to build phpredis on Windows.
See dedicated page.
Description: Creates a Redis client
$redis = new Redis();
phpredis throws a RedisException object if it can't reach the Redis server. That can happen in case of connectivity issues,
if the Redis service is down, or if the redis host is overloaded. In any other problematic case that does not involve an
unreachable server (such as a key not existing, an invalid command, etc), phpredis will return FALSE
.
Description: Available Redis Constants
Redis data types, as returned by type
Redis::REDIS_STRING - String
Redis::REDIS_SET - Set
Redis::REDIS_LIST - List
Redis::REDIS_ZSET - Sorted set
Redis::REDIS_HASH - Hash
Redis::REDIS_NOT_FOUND - Not found / other
@TODO: OPT_SERIALIZER, AFTER, BEFORE,...
- connect, open - Connect to a server
- pconnect, popen - Connect to a server (persistent)
- auth - Authenticate to the server
- select - Change the selected database for the current connection
- close - Close the connection
- setOption - Set client option
- getOption - Get client option
- ping - Ping the server
- echo - Echo the given string
Description: Connects to a Redis instance.
host: string. can be a host, or the path to a unix domain socket
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.
Description: 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.
Description: Authenticate the connection using a password. Warning: The password is sent in plain-text over the network.
STRING: password
BOOL: TRUE
if the connection is authenticated, FALSE
otherwise.
$redis->auth('foobared');
Description: Change the selected database for the current connection.
INTEGER: dbindex, the database number to switch to.
TRUE
in case of success, FALSE
in case of failure.
See method for example: move
Description: Disconnects from the Redis instance, except when pconnect
is used.
Description: Set client option.
parameter name
parameter value
BOOL: TRUE
on success, FALSE
on error.
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); // don't serialize data
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); // use built-in serialize/unserialize
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // use igBinary serialize/unserialize
$redis->setOption(Redis::OPT_PREFIX, 'myAppName:'); // use custom prefix on all keys
Description: Get client option.
parameter name
Parameter value.
$redis->getOption(Redis::OPT_SERIALIZER); // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY.
Description: Check the current connection status
(none)
STRING: +PONG
on success. Throws a RedisException object on connectivity error, as described above.
Description: Sends a string to Redis, which replies with the same string
STRING: The message to send.
STRING: the same message.
- bgrewriteaof - Asynchronously rewrite the append-only file
- bgsave - Asynchronously save the dataset to disk (in background)
- config - Get or Set the Redis server configuration parameters
- dbSize - Return the number of keys in selected database
- flushAll - Remove all keys from all databases
- flushDB - Remove all keys from the current database
- info - Get information and statistics about the server
- lastSave - Get the timestamp of the last disk save
- resetStat - Reset the stats returned by info method.
- save - Synchronously save the dataset to disk (wait to complete)
- slaveof - Make the server a slave of another instance, or promote it to master
- time - Return the current server time
Description: Start the background rewrite of AOF (Append-Only File)
None.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->bgrewriteaof();
Description: Asynchronously save the dataset to disk (in background)
None.
BOOL: TRUE
in case of success, FALSE
in case of failure. If a save is already running, this command will fail and return FALSE
.
$redis->bgSave();
Description: Get or Set the Redis server configuration parameters.
operation (string) either GET
or SET
key string for SET
, glob-pattern for GET
. See http://redis.io/commands/config-get for examples.
value optional string (only for SET
)
Associative array for GET
, key -> value
bool for SET
$redis->config("GET", "*max-*-entries*");
$redis->config("SET", "dir", "/var/run/redis/dumps/");
Description: Return the number of keys in selected database.
None.
INTEGER: DB size, in number of keys.
$count = $redis->dbSize();
echo "Redis has $count keys\n";
Description: Remove all keys from all databases.
None.
BOOL: Always TRUE
.
$redis->flushAll();
Description: Remove all keys from the current database.
None.
BOOL: Always TRUE
.
$redis->flushDB();
Description: Get information and statistics about the server
Returns an associative array that provides information about the server. Passing no arguments to INFO will call the standard REDIS INFO command, which returns information such as the following:
- redis_version
- arch_bits
- uptime_in_seconds
- uptime_in_days
- connected_clients
- connected_slaves
- used_memory
- changes_since_last_save
- bgsave_in_progress
- last_save_time
- total_connections_received
- total_commands_processed
- role
You can pass a variety of options to INFO (per the Redis documentation), which will modify what is returned.
option: The option to provide redis (e.g. "COMMANDSTATS", "CPU")
$redis->info(); /* standard redis INFO command */
$redis->info("COMMANDSTATS"); /* Information on the commands that have been run (>=2.6 only)
$redis->info("CPU"); /* just CPU information from Redis INFO */
Description: Returns the timestamp of the last disk save.
None.
INT: timestamp.
$redis->lastSave();
Description: Reset the stats returned by info method.
These are the counters that are reset:
- Keyspace hits
- Keyspace misses
- Number of commands processed
- Number of connections received
- Number of expired keys
None.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->resetStat();
Description: Synchronously save the dataset to disk (wait to complete)
None.
BOOL: TRUE
in case of success, FALSE
in case of failure. If a save is already running, this command will fail and return FALSE
.
$redis->save();
Description: Changes the slave status
Either host (string) and port (int), or no parameter to stop being a slave.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->slaveof('10.0.1.7', 6379);
/* ... */
$redis->slaveof();
Description: Return the current server time.
(none)
If successfull, the time will come back as an associative array with element zero being the unix timestamp, and element one being microseconds.
$redis->time();
- append - Append a value to a key
- bitcount - Count set bits in a string
- bitop - Perform bitwise operations between strings
- decr, decrBy - Decrement the value of a key
- get - Get the value of a key
- getBit - Returns the bit value at offset in the string value stored at key
- getRange - Get a substring of the string stored at a key
- getSet - Set the string value of a key and return its old value
- incr, incrBy - Increment the value of a key
- incrByFloat - Increment the float value of a key by the given amount
- mGet, getMultiple - Get the values of all the given keys
- mSet, mSetNX - Set multiple keys to multiple values
- set - Set the string value of a key
- setBit - Sets or clears the bit at offset in the string value stored at key
- setex, psetex - Set the value and expiration of a key
- setnx - Set the value of a key, only if the key does not exist
- setRange - Overwrite part of a string at key starting at the specified offset
- strlen - Get the length of the value stored in a key
- del, delete - Delete a key
- dump - Return a serialized version of the value stored at the specified key.
- exists - Determine if a key exists
- expire, setTimeout, pexpire - Set a key's time to live in seconds
- expireAt, pexpireAt - Set the expiration for a key as a UNIX timestamp
- keys, getKeys - Find all keys matching the given pattern
- migrate - Atomically transfer a key from a Redis instance to another one
- move - Move a key to another database
- object - Inspect the internals of Redis objects
- persist - Remove the expiration from a key
- randomKey - Return a random key from the keyspace
- rename, renameKey - Rename a key
- renameNx - Rename a key, only if the new key does not exist
- type - Determine the type stored at key
- sort - Sort the elements in a list, set or sorted set
- ttl, pttl - Get the time to live for a key
- restore - Create a key using the provided serialized value, previously obtained with dump.
Description: 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');
Description: 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');
Description: Set the string value in argument as value of the key, with a time to live. PSETEX uses a TTL in milliseconds.
Key TTL Value
Bool TRUE
if the command is successful.
$redis->setex('key', 3600, 'value'); // sets key → value, with 1h TTL.
$redis->psetex('key', 100, 'value'); // sets key → value, with 0.1 sec TTL.
Description: 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 */
Description: 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 */
Description: 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 */
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.
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 */
Description: Increment the key with floating point precision.
key
value: (float) value that will be added to the key
FLOAT the new value
$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); /* 3.5 */
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.
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 */
Description: 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->mGet(array('key1', 'key2', 'key3')); /* array('value1', 'value2', 'value3');
$redis->mGet(array('key0', 'key1', 'key5')); /* array(`FALSE`, 'value2', `FALSE`);
Description: Sets a value and returns the previous entry at that key.
Key: key
STRING: value
A string, the previous value located at this key.
$redis->set('x', '42');
$exValue = $redis->getSet('x', 'lol'); // return '42', replaces x by 'lol'
$newValue = $redis->get('x')' // return 'lol'
Description: Returns a random key.
None.
STRING: an existing key in redis.
$key = $redis->randomKey();
$surprise = $redis->get($key); // who knows what's in there.
Description: Moves a key to a different database.
Key: key, the key to move.
INTEGER: dbindex, the database number to move the key to.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$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
Description: Renames a key.
STRING: srckey, the key to rename.
STRING: dstkey, the new name for the key.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->set('x', '42');
$redis->rename('x', 'y');
$redis->get('y'); // → 42
$redis->get('x'); // → `FALSE`
Description: Same as rename, but will not replace a key if the destination already exists. This is the same behaviour as setNx.
Description: Sets an expiration date (a timeout) on an item. pexpire requires a TTL in milliseconds.
Key: key. The key that will disappear.
Integer: ttl. The key's remaining Time To Live, in seconds.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->set('x', '42');
$redis->setTimeout('x', 3); // x will disappear in 3 seconds.
sleep(5); // wait 5 seconds
$redis->get('x'); // will return `FALSE`, as 'x' has expired.
Description: Sets an expiration date (a timestamp) on an item. pexpireAt requires a timestamp in milliseconds.
Key: key. The key that will disappear.
Integer: Unix timestamp. The key's date of death, in seconds from Epoch time.
BOOL: TRUE
in case of success, FALSE
in case of failure.
$redis->set('x', '42');
$now = time(NULL); // current timestamp
$redis->expireAt('x', $now + 3); // x will disappear in 3 seconds.
sleep(5); // wait 5 seconds
$redis->get('x'); // will return `FALSE`, as 'x' has expired.
Description: Returns the keys that match a certain pattern.
STRING: pattern, using '*' as a wildcard.
Array of STRING: The keys that match a certain pattern.
$allKeys = $redis->keys('*'); // all keys will match this.
$keyWithUserPrefix = $redis->keys('user*');
Description: Describes the object pointed to by a key.
The information to retrieve (string) and the key (string). Info can be one of the following:
- "encoding"
- "refcount"
- "idletime"
STRING for "encoding", LONG for "refcount" and "idletime", FALSE
if the key doesn't exist.
$redis->object("encoding", "l"); // → ziplist
$redis->object("refcount", "l"); // → 1
$redis->object("idletime", "l"); // → 400 (in seconds, with a precision of 10 seconds).
Description: Returns the type of data pointed by a given key.
Key: key
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
$redis->type('key');
Description: Append specified string to the string stored in specified key.
Key Value
INTEGER: Size of the value after the append
$redis->set('key', 'value1');
$redis->append('key', 'value2'); /* 12 */
$redis->get('key'); /* 'value1value2' */
Description: Return a substring of a larger string
Note: substr also supported but deprecated in redis.
key start end
STRING: the substring
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5); /* 'string' */
$redis->getRange('key', -5, -1); /* 'value' */
Description: Changes a substring of a larger string.
key
offset
value
STRING: the length of the string after it was modified.
$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis"); /* returns 11 */
$redis->get('key'); /* "Hello redis" */
Description: Get the length of a string value.
key
INTEGER
$redis->set('key', 'value');
$redis->strlen('key'); /* 5 */
Description: Return a single bit out of a larger string
key
offset
LONG: the bit value (0 or 1)
$redis->set('key', "\x7f"); // this is 0111 1111
$redis->getBit('key', 0); /* 0 */
$redis->getBit('key', 1); /* 1 */
Description: Changes a single bit of a string.
key
offset
value: bool or int (1 or 0)
LONG: 0 or 1, the value of the bit before it was set.
$redis->set('key', "*"); // ord("*") = 42 = 0x2f = "0010 1010"
$redis->setBit('key', 5, 1); /* returns 0 */
$redis->setBit('key', 7, 1); /* returns 0 */
$redis->get('key'); /* chr(0x2f) = "/" = b("0010 1111") */
Description: Bitwise operation on multiple keys.
operation: either "AND", "OR", "NOT", "XOR"
ret_key: return key
key1
key2...
LONG: The size of the string stored in the destination key.
Description: Count bits in a string.
key
LONG: The number of bits set to 1 in the value behind the input key.
Description: Sort the elements in a list, set or sorted set.
Key: key Options: array(key => value, ...) - optional, with the following keys and values:
'by' => 'some_pattern_*',
'limit' => array(0, 1),
'get' => 'some_other_pattern_*' or an array of patterns,
'sort' => 'asc' or 'desc',
'alpha' => TRUE,
'store' => 'external-key'
An array of values, or a number corresponding to the number of elements stored if that was used.
$redis->delete('s');
$redis->sadd('s', 5);
$redis->sadd('s', 4);
$redis->sadd('s', 2);
$redis->sadd('s', 1);
$redis->sadd('s', 3);
var_dump($redis->sort('s')); // 1,2,3,4,5
var_dump($redis->sort('s', array('sort' => 'desc'))); // 5,4,3,2,1
var_dump($redis->sort('s', array('sort' => 'desc', 'store' => 'out'))); // (int)5
Description: Returns the time to live left for a given key, in seconds. If the key doesn't exist, FALSE
is returned. pttl returns a time in milliseconds.
Key: key
Long, the time left to live in seconds.
$redis->ttl('key');
Description: Remove the expiration timer from a key.
Key: key
BOOL: TRUE
if a timeout was removed, FALSE
if the key didn’t exist or didn’t have an expiration timer.
$redis->persist('key');
Description: Sets multiple key-value pairs in one atomic command. MSETNX only returns TRUE if all the keys were set (see SETNX).
Pairs: array(key => value, ...)
Bool TRUE
in case of success, FALSE
in case of failure.
$redis->mset(array('key0' => 'value0', 'key1' => 'value1'));
var_dump($redis->get('key0'));
var_dump($redis->get('key1'));
Output:
string(6) "value0"
string(6) "value1"
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.
key string
The Redis encoded value of the key, or FALSE if the key doesn't exist
$redis->set('foo', 'bar');
$val = $redis->dump('foo'); // $val will be the Redis encoded key value
Description: Restore a key from the result of a DUMP operation.
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)
$redis->set('foo', 'bar');
$val = $redis->dump('foo');
$redis->restore('bar', 0, $val); // The key 'bar', will now be equal to the key 'foo'
Description: Migrates a key to a different Redis instance.
host string. The destination host
port integer. The TCP port to connect to.
key string. The key to migrate.
destination-db integer. The target DB.
timeout integer. The maximum amount of time given to this transfer.
$redis->migrate('backup', 6379, 'foo', 0, 3600);
- hDel - Delete one or more hash fields
- hExists - Determine if a hash field exists
- hGet - Get the value of a hash field
- hGetAll - Get all the fields and values in a hash
- hIncrBy - Increment the integer value of a hash field by the given number
- hIncrByFloat - Increment the float value of a hash field by the given amount
- hKeys - Get all the fields in a hash
- hLen - Get the number of fields in a hash
- hMGet - Get the values of all the given hash fields
- hMSet - Set multiple hash fields to multiple values
- hSet - Set the string value of a hash field
- hSetNx - Set the value of a hash field, only if the field does not exist
- hVals - Get all the values in a hash
Description: Adds a value to the hash stored at key. If this value is already in the hash, FALSE
is returned.
key
hashKey
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.
$redis->delete('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" */
Description: Adds a value to the hash stored at key only if this field isn't already in the hash.
BOOL TRUE
if the field was set, FALSE
if it was already present.
$redis->delete('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. */
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.
key
hashKey
STRING The value, if the command executed successfully
BOOL FALSE
in case of failure
Description: Returns the length of a hash, in number of items
key
LONG the number of items in a hash, FALSE
if the key doesn't exist or isn't a hash.
$redis->delete('h')
$redis->hSet('h', 'key1', 'hello');
$redis->hSet('h', 'key2', 'plop');
$redis->hLen('h'); /* returns 2 */
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.
key
hashKey
BOOL TRUE
in case of success, FALSE
in case of failure
Description: Returns the keys in a hash, as an array of strings.
Key: key
An array of elements, the keys of the hash. This works like PHP's array_keys().
$redis->delete('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hKeys('h'));
Output:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
}
The order is random and corresponds to redis' own internal representation of the set structure.
Description: Returns the values in a hash, as an array of strings.
Key: key
An array of elements, the values of the hash. This works like PHP's array_values().
$redis->delete('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hVals('h'));
Output:
array(4) {
[0]=>
string(1) "x"
[1]=>
string(1) "y"
[2]=>
string(1) "z"
[3]=>
string(1) "t"
}
The order is random and corresponds to redis' own internal representation of the set structure.
Description: Returns the whole hash, as an array of strings indexed by strings.
Key: key
An array of elements, the contents of the hash.
$redis->delete('h');
$redis->hSet('h', 'a', 'x');
$redis->hSet('h', 'b', 'y');
$redis->hSet('h', 'c', 'z');
$redis->hSet('h', 'd', 't');
var_dump($redis->hGetAll('h'));
Output:
array(4) {
["a"]=>
string(1) "x"
["b"]=>
string(1) "y"
["c"]=>
string(1) "z"
["d"]=>
string(1) "t"
}
The order is random and corresponds to redis' own internal representation of the set structure.
Description: Verify if the specified member exists in a key.
key
memberKey
BOOL: If the member exists in the hash table, return TRUE
, otherwise return FALSE
.
$redis->hSet('h', 'a', 'x');
$redis->hExists('h', 'a'); /* TRUE */
$redis->hExists('h', 'NonExistingKey'); /* FALSE */
Description: Increments the value of a member from a hash by a given amount.
key
member
value: (integer) value that will be added to the member's value
LONG the new value
$redis->delete('h');
$redis->hIncrBy('h', 'x', 2); /* returns 2: h[x] = 2 now. */
$redis->hIncrBy('h', 'x', 1); /* h[x] ← 2 + 1. Returns 3 */
Description: Increments the value of a hash member by the provided float value
key
member
value: (float) value that will be added to the member's value
FLOAT the new value
$redis->delete('h');
$redis->hIncrByFloat('h','x', 1.5); /* returns 1.5: h[x] = 1.5 now */
$redis->hIncrByFLoat('h', 'x', 1.5); /* returns 3.0: h[x] = 3.0 now */
$redis->hIncrByFloat('h', 'x', -3.0); /* returns 0.0: h[x] = 0.0 now */
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.
key
members: key → value array
BOOL
$redis->delete('user:1');
$redis->hMset('user:1', array('name' => 'Joe', 'salary' => 2000));
$redis->hIncrBy('user:1', 'salary', 100); // Joe earns 100 more now.
Description: Retrieve the values associated to the specified fields in the hash.
key
memberKeys Array
Array An array of elements, the values of the specified fields in the hash, with the hash keys as array keys.
$redis->delete('h');
$redis->hSet('h', 'field1', 'value1');
$redis->hSet('h', 'field2', 'value2');
$redis->hmGet('h', array('field1', 'field2')); /* returns array('field1' => 'value1', 'field2' => 'value2') */
- blPop, brPop - Remove and get the first/last element in a list
- brpoplpush - Pop a value from a list, push it to another list and return it
- lIndex, lGet - Get an element from a list by its index
- lInsert - Insert an element before or after another element in a list
- lLen, lSize - Get the length/size of a list
- lPop - Remove and get the first element in a list
- lPush - Prepend one or multiple values to a list
- lPushx - Prepend a value to a list, only if the list exists
- lRange, lGetRange - Get a range of elements from a list
- lRem, lRemove - Remove elements from a list
- lSet - Set the value of an element in a list by its index
- lTrim, listTrim - Trim a list to the specified range
- rPop - Remove and get the last element in a list
- rpoplpush - Remove the last element in a list, append it to another list and return it (redis >= 1.1)
- rPush - Append one or multiple values to a list
- rPushx - Append a value to a list, only if the list exists
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. 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*/
Description: A blocking version of rpoplpush
, with an integral timeout in the third parameter.
Key: srckey
Key: dstkey
Long: timeout
STRING The element that was moved in case of success, FALSE
in case of timeout.
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.
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` */
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.
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 */
Description: 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' ] */
Description: 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' ] */
Description: 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' ] */
Description: 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') */
Description: 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.
Note: The argument order is not the same as in the Redis documentation. This difference is kept for compatibility reasons.
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') */
Description: 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' */
Description: 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') */
Description: Returns and removes the last 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' ] */
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)
Key: srckey
Key: dstkey
STRING The element that was moved in case of success, FALSE
in case of failure.
$redis->delete('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));
Output:
< 10000 div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="string(3) "abc" array(1) { [0]=> string(3) "def" } array(3) { [0]=> string(3) "abc" [1]=> string(3) "456" [2]=> string(3) "123" }">string(3) "abc"
array(1) {
[0]=>
string(3) "def"
}
array(3) {
[0]=>
string(3) "abc"
[1]=>
string(3) "456"
[2]=>
string(3) "123"
}