The phpredis extension provides an API for communicating with the Redis key-value store. It is released under the PHP License, version 3.01. This code has been developed and maintained by Owlient from November 2009 to March 2011.
You can send comments, patches, questions here on github, to n.favrefelix@gmail.com (@yowgi), or to michael.grunder@gmail.com (@grumi78).
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.
You can install install it using Homebrew:
- Get homebrew-php
brew install php55-redis
(or php53-redis, php54-redis)
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)
reserved: should be NULL if retry_interval is specified
retry_interval: int, value in milliseconds (optional)
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.
$redis->connect('127.0.0.1', 6379, 1, NULL, 100); // 1 sec timeout, 100ms delay between reconnection attempts.
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
retry_interval: int, value in milliseconds (optional)
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
close
F438Description: 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
/* 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);
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
- slowlog - Access the Redis slowlog entries
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();
Description: Access the Redis slowlog
Operation (string): This can be either GET
, LEN
, or RESET
Length (integer), optional: If executing a SLOWLOG GET
command, you can pass an optional length.
The return value of SLOWLOG will depend on which operation was performed. SLOWLOG GET: Array of slowlog entries, as provided by Redis SLOGLOG LEN: Integer, the length of the slowlog SLOWLOG RESET: Boolean, depending on success
// Get ten slowlog entries
$redis->slowlog('get', 10);
// Get the default number of slowlog entries
$redis->slowlog('get');
// Reset our slowlog
$redis->slowlog('reset');
// Retrieve slowlog length
$redis->slowlog('len');
- append - Append a value to a key
- bitcount - Count set bits in a string
- bitop - Perform bitwise operations between strings
- decr, decrBy - Decrement the value of a key
- get - Get the value of a key
- getBit - Returns the bit value at offset in the string value stored at key
- getRange - Get a substring of the string stored at a key
- getSet - Set the string value of a key and return its old value
- incr, incrBy - Increment the value of a key
- incrByFloat - Increment the float value of a key by the given amount
- mGet, getMultiple - Get the values of all the given keys
- mSet, mSetNX - Set multiple keys to multiple values
- set - Set the string value of a key
- setBit - Sets or clears the bit at offset in the string value stored at key
- setex, psetex - Set the value and expiration of a key
- setnx - Set the value of a key, only if the key does not exist
- setRange - Overwrite part of a string at key starting at the specified offset
- strlen - Get the length of the value stored in a key
- 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
- scan - Scan for keys in the keyspace (Redis >= 2.8.0)
- 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. If you're using Redis >= 2.6.12, you can pass extended options as explained below
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
Bool TRUE
if the command is successful.
// 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', Array('nx', 'ex'=>10));
// Will set a key, if it does exist, with a ttl of 1000 miliseconds
$redis->set('key', 'value', Array('xx', 'px'=>1000));
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); /* 4 */
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: Scan the keyspace for keys
LONG (reference): Iterator, initialized to NULL STRING, Optional: Pattern to match LONG, Optional: Count of keys per iteration (only a suggestion to Redis)
Array, boolean: This function will return an array of keys or FALSE if there are no more keys
$it = NULL; /* Initialize our iterator to NULL */
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); /* retry when we get no keys back */
while($arr_keys = $redis->scan($it)) {
foreach($arr_keys as $str_key) {
echo "Here is a key: $str_key\n";
}
echo "No more keys to scan!\n";
}
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.
< 10000 div class="markdown-heading" dir="auto">