Skip to content

phpredis/phpredis

develop
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
September 23, 2023 14:46
November 2, 2012 10:51
March 1, 2023 10:02
October 17, 2017 17:08
November 8, 2022 14:59
November 8, 2022 14:59
October 22, 2023 21:12
November 8, 2022 14:49
October 25, 2023 08:23
February 4, 2023 12:47
November 8, 2022 14:59
September 17, 2010 13:57
October 22, 2023 19:16
October 22, 2023 21:12
October 30, 2023 10:51
December 24, 2022 13:37
September 13, 2023 18:28

README.md

PhpRedis

Build Status Coverity Scan Build Status PHP version

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 michael.grunder@gmail.com (Twitter, Mastodon), p.yatsukhnenko@gmail.com (@yatsukhnenko), or n.favrefelix@gmail.com (@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 PayPal

Sponsors

Audiomack.com Bluehost.com Object Cache Pro OpenLMS.net

Table of contents


  1. Installing/Configuring
  2. Classes and methods

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 and session.save_path in your php.ini to tell phpredis where to store the sessions:

session.save_handler = redis
session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2&read_timeout=2.5"

session.save_path can have a simple host:port format too, but you need to provide the tcp:// scheme if you want to use the parameters. The following parameters are available:

  • weight (integer): the weight of a host is used in comparison with the others in order to customize the session distribution on several hosts. If host A has twice the weight of host B, it will get twice the amount of sessions. In the example, host1 stores 20% of all the sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/(1+2+2)). The target host is determined once and for all at the start of the session, and doesn't change. The default weight is 1.
  • timeout (float): the connection timeout to a redis host, expressed in seconds. If the host is unreachable in that amount of time, the session storage will be unavailable for the client. The default timeout is very high (86400 seconds).
  • persistent (integer, should be 1 or 0): defines if a persistent connection should be used.
  • 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

Classes and methods


Usage

  1. Class Redis
  2. Class RedisException
  3. Predefined constants

Class Redis


Description: Creates a Redis client

Example
$redis = new Redis();

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
$redis = new Redis([
    'host' => '127.0.0.1',
    'port' => 6379,
    'connectTimeout' => 2.5,
    'auth' => ['phpredis', 'phpredis'],
    'ssl' => ['verify_peer' => false],
    'backoff' => [
        'algorithm' => Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER,
        'base' => 500,
        'cap' => 750,
    ],
]);
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

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,...

Connection

  1. connect, open - Connect to a server
  2. pconnect, popen - Connect to a server (persistent)
  3. auth - Authenticate to the server
  4. select - Change the selected database for the current connection
  5. swapdb - Swaps two Redis databases
  6. close - Close the connection
  7. setOption - Set client option
  8. getOption - Get client option
  9. ping - Ping the server
  10. echo - Echo the given string

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
$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.

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 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

Parameters

STRING: The message to send.

Return value

STRING: the same message.

Retry and backoff

  1. Maximum retries
  2. Backoff algorithms

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
$redis->setOption(Redis::OPT_MAX_RETRIES, 5);
$redis->getOption(Redis::OPT_MAX_RETRIES);

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:

  • Default: Redis::BACKOFF_ALGORITHM_DEFAULT
  • Decorrelated jitter: Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER
  • Full jitter: Redis::BACKOFF_ALGORITHM_FULL_JITTER
  • Equal jitter: Redis::BACKOFF_ALGORITHM_EQUAL_JITTER
  • Exponential: Redis::BACKOFF_ALGORITHM_EXPONENTIAL
  • Uniform: Redis::BACKOFF_ALGORITHM_UNIFORM
  • Constant: Redis::BACKOFF_ALGORITHM_CONSTANT

These algorithms depend on the base and cap parameters, both in milliseconds, which you can set using the Redis::OPT_BACKOFF_BASE and Redis::OPT_BACKOFF_CAP options, respectively.

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

Server

  1. acl - Manage Redis ACLs
  2. bgRewriteAOF - Asynchronously rewrite the append-only file
  3. bgSave - Asynchronously save the dataset to disk (in background)
  4. config - Get or Set the Redis server configuration parameters
  5. dbSize - Return the number of keys in selected database
  6. flushAll - Remove all keys from all databases
  7. flushDb - Remove all keys from the current database
  8. info - Get information and statistics about the server
  9. lastSave - Get the timestamp of the last disk save
  10. save - Synchronously save the dataset to disk (wait to complete)
  11. slaveOf - Make the server a slave of another instance, or promote it to master
  12. time - Return the current server time
  13. slowLog - Access the Redis slowLog entries

acl


Description: Execute the Redis ACL command.

Parameters

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.

Prototype
$redis->config(string $operation, string|array|null $key = NULL, ?string $value = NULL): mixed;
Return value

Associative array for GET, key(s) -> value(s)
bool for SET, RESETSTAT, and REWRITE

Examples
$redis->config("GET", "*max-*-entries*");
$redis->config("SET", ['timeout', 'loglevel']);
$redis->config("SET", "dir", "/var/run/redis/dumps/");
$redis->config("SET", ['timeout' => 128, 'loglevel' => 'warning']);
$redis->config('RESETSTAT');

dbSize


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.

Example
$redis->slaveOf('10.0.1.7', 6379);
/* ... */
$redis->slaveOf();

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
$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');

Keys and Strings

Strings


  • 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

Keys


  • del, delete, unlink - 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.

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

Bool TRUE 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.

Parameters

Key TTL Value

Return value

Bool TRUE if the command is successful.

Examples
$redis->setEx('key', 3600, 'value'); // sets key → value, with 1h TTL.
$redis->pSetEx('key', 100, 'value'); // sets key → value, with 0.1 sec TTL.

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
$redis->setNx('key', 'value'); /* return TRUE */
$redis->setNx('key', 'value'); /* return FALSE */

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 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.

exists


Description: Verify if the specified key exists.

Parameters

key

Return value

long: The number of keys tested that do exist.

Examples
$redis->set('key', 'value');
$redis->exists('key'); /* 1 */
$redis->exists('NonExistingKey'); /* 0 */

$redis->mset(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz']);
$redis->exists(['foo', 'bar', 'baz']); /* 3 */
$redis->exists('foo', 'bar', 'baz'); /* 3 */

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

Examples
$redis->set('key1', 'value1');
$redis->set('key2', 'value2');
$redis->set('key3', 'value3');
$redis->mGet(['key1', 'key2', 'key3']); /* ['value1', 'value2', 'value3'];
$redis->mGet(['key0', 'key1', 'key5']); /* [`FALSE`, 'value1', `FALSE`];

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.

Example
$redis->set('x', '42');
$redis->rename('x', 'y');
$redis->get('y'); 	// → 42
$redis->get('x'); 	// → `FALSE`

Note: renameKey is an alias for rename 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
public function expire(string $key, int $seconds, ?string $mode = NULL): Redis|bool;
public function pexpire(string $key, int $milliseconds, ?string $mode = NULL): Redis|bool;
Return value

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.

Prototype
public function expireat(string $key, int $unix_timestamp, ?string $mode = NULL): Redis|bool;
public function pexpireat(string $key, int $unix_timestamp_millis, ?string $mode = NULL): Redis|bool;
Return value

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 that
    if ($arr_keys !== FALSE) {
        foreach($arr_keys as $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_keys as $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.

Parameters

Key Value

Return value

INTEGER: Size of the value after the append

Example
$redis->set('key', 'value1');
$redis->append('key', 'value2'); /* 12 */
$redis->get('key'); /* 'value1value2' */

getRange


Description: Return a substring of a larger string

Parameters

key
start
end

Return value

STRING: the substring

Example
$redis->set('key', 'string value');
$redis->getRange('key', 0, 5); /* 'string' */
$redis->getRange('key', -5, -1); /* 'value' */

Note: substr is an alias for getRange 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
$redis->set('key', 'Hello world');
$redis->setRange('key', 6, "redis"); /* returns 11 */
$redis->get('key'); /* "Hello redis" */

strLen


Description: Get the length of a string value.

Parameters

key

Return value

INTEGER

Example
$redis->set('key', 'value');
$redis->strlen('key'); /* 5 */

getBit


Description: Return a single bit out of a larger string

Parameters

key
offset

Return value

LONG: the bit value (0 or 1)

Example
$redis->set('key', "\x7f"); // this is 0111 1111
$redis->getBit('key', 0); /* 0 */
$redis->getBit('key', 1); /* 1 */

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
$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") */

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:

    'by' => 'some_pattern_*',
    'limit' => [0, 1],
    'get' => 'some_other_pattern_*' or an array of patterns,
    'sort' => 'asc' or 'desc',
    'alpha' => TRUE,
    'store' => 'external-key'
Return value

An array of values, or a number corresponding to the number of elements stored if that was used.

Example
$redis->del('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', ['sort' => 'desc'])); // 5,4,3,2,1
var_dump($redis->sort('s', ['sort' => 'desc', 'store' => 'out'])); // (int)5

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
$redis->ttl('key');

persist


Description: Remove the expiration timer from a key.

Parameters

Key: key