diff --git a/INSTALL.md b/INSTALL.md index 449275f1db..496450bb9b 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,18 +1,30 @@ -# Installation with PIE from packagist +# Installation options -To pull latest stable released version, from [packagist](https://packagist.org/packages/phpredis/phpredis) +phpredis can be installed from PECL, from source, or with pre-built packages provided by most distributions. -~~~ +## PIE (PHP Installer for Extensions) + +If you use [PIE](https://github.com/cuaxin/pie) to install PHP extensions from [Packagist](https://packagist.org/packages/phpredis/phpredis): + +```bash pie install phpredis/phpredis -~~~ +``` -# Installation from pecl +You can also install a specific tag: -To pull latest stable released version, from [pecl](https://pecl.php.net/package/redis) +```bash +pie install phpredis/phpredis:6.2.0 +pie install phpredis/phpredis:6.3.0RC1 +``` +**NOTE**: PIE is recommended over PECL for installing extensions. + +## PECL -~~~ +Pull the latest stable release from [PECL](https://pecl.php.net/package/redis): + +```bash pecl install redis -~~~ +``` Configure options can be passed as well: @@ -20,89 +32,46 @@ Configure options can be passed as well: pecl install --configureoptions="enable-redis-msgpack='yes' enable-redis-igbinary='yes'" redis ``` -# Installation from sources - -To build this extension for the sources tree: +## Build from source -~~~ +```bash git clone https://github.com/phpredis/phpredis.git cd phpredis phpize ./configure [--enable-redis-igbinary] [--enable-redis-msgpack] [--enable-redis-lzf [--with-liblzf[=DIR]]] [--enable-redis-zstd] [--enable-redis-lz4] make && make install -~~~ - -If you would like phpredis to serialize your data using the igbinary library, run configure with `--enable-redis-igbinary`. -If you would like to use the msgpack serializer, run configure with `--enable-redis-msgpack` (note: Requires php-msgpack >= 2.0.3) -The extension also may compress data before sending it to Redis server, if you run configure with `--enable-redis-lzf`. If you want to use lzf library pre-installed into your system use `--with-liblzf` configuration option to specify the path where to search files. -`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](./README.md#class-redis) (and [RedisException](./README.md#class-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. +- `--enable-redis-igbinary` enables igbinary serialization. +- `--enable-redis-msgpack` enables msgpack serialization (requires php-msgpack >= 2.0.3). +- `--enable-redis-lzf` / `--with-liblzf` enable LZF compression. +- `--enable-redis-zstd` / `--enable-redis-lz4` enable additional compression codecs. +After `make install`, enable the extension (for example `echo "extension=redis.so" > /etc/php.d/redis.ini`) and confirm with `php -m | grep redis`. # Binary packages -Most distributions provides pre-build binary packages of this extension. - -## Windows: - -Follow the DLL link on the [https://pecl.php.net/package/redis](https://pecl.php.net/package/redis) page or use [https://windows.php.net/downloads/pecl/releases/redis/](https://windows.php.net/downloads/pecl/releases/redis/) - -## Fedora +Most distributions provide a packaged extension. Package names vary by PHP version; replace the PHP version in the command if needed. -Fedora users can install the package from the official repository. +- Debian / Ubuntu: `sudo apt install php-redis` +- Fedora: `sudo dnf install php-redis` (provided as php-pecl-redis) +- RHEL / CentOS / Alma / Rocky: enable EPEL/Remi if required, then `sudo dnf install php-pecl-redis` +- openSUSE Leap / Tumbleweed: `sudo zypper install php8-redis` (or matching PHP slot) +- Arch Linux / Manjaro: `sudo pacman -S php-redis` +- Alpine: `sudo apk add php82-redis` (replace 82 with your PHP minor version) +- macOS (Homebrew): `brew install php && pecl install redis` +- Windows: download the DLL from [PECL](https://pecl.php.net/package/redis) or [windows.php.net](https://windows.php.net/downloads/pecl/releases/redis/) +- MacPorts: `sudo port install php82-redis` (or the desired PHP slot) -### Fedora ≥ 40, Version 6 +# Notes for Docker -Installation of the [php-pecl-redis6](https://src.fedoraproject.org/rpms/php-pecl-redis6/) package: +If you are building on the official `php` Docker images with Debian/Alpine bases, you can install via PECL and enable the extension: -~~~ -dnf install php-redis -~~~ - -## CentOS / RHEL and clones - -Installation of the php-pecl-redis6 package, available for PHP ≥ 8.3: - -~~~ -dnf install php-redis -~~~ - -### openSUSE ≥ 15.1 - -Installation of the [php7-redis](https://software.opensuse.org/package/php7-redis?search_term=php7-redis) package: - -~~~ -zypper in php7-redis -~~~ - - -# Installation on OSX - -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 ](http://www.tumblr.com/tagged/phpredis). - -See also: [Install Redis & PHP Extension PHPRedis with Macports](http://www.lecloud.net/post/3378834922/install-redis-php-extension-phpredis-with-macports). - -You can install it using MacPorts: - -- [Get macports-php](https://www.macports.org/) -- `sudo port install php56-redis` (or php53-redis, php54-redis, php55-redis, php70-redis, php71-redis, php72-redis, php73-redis, php74-redis) - -# Building on Windows +```bash +pecl install redis \ + && docker-php-ext-enable redis +``` -See [instructions from @char101](https://github.com/phpredis/phpredis/issues/213#issuecomment-11361242) on how to build phpredis on Windows. +# Additional resources +This extension exports [Redis](./README.md#class-redis) and [RedisException](./README.md#class-redisexception). A PHP stub for IDE completion is available at https://github.com/ukko/phpredis-phpdoc. diff --git a/README.md b/README.md index 41930b6743..4ea03a49d3 100644 --- a/README.md +++ b/README.md @@ -40,25 +40,14 @@ The best way to support the project is through [GitHub Sponsors](https://github. * [Redis Cluster support](./cluster.md#readme) * [Redis Sentinel support](./sentinel.md#readme) * [Running the unit tests](#running-the-unit-tests) -2. [API Documentation](#api-documentation) 3. [Classes and methods](#classes-and-methods) * [Usage](#usage) * [Connection](#connection) * [Retry and backoff](#retry-and-backoff) - * [Server](#server) - * [Keys and strings](#keys-and-strings) - * [Hashes](#hashes) - * [Lists](#lists) - * [Sets](#sets) - * [Sorted sets](#sorted-sets) - * [HyperLogLogs](#hyperloglogs) - * [Geocoding](#geocoding) - * [Streams](#streams) - * [Pub/sub](#pubsub) * [Transactions](#transactions) - * [Scripting](#scripting) * [Local Helper Methods](#local-helper-methods) * [Introspection](#introspection) +2. [API Documentation](#api-documentation) ## Installing/Configuring @@ -87,22 +76,22 @@ phpredis can also connect to a unix domain socket: `session.save_path = "unix:// #### Examples Multiple Redis servers: -~~~ +```ini 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" -~~~ +``` Login to Redis using username and password: -~~~ +```ini session.save_handler = redis session.save_path = "tcp://127.0.0.1:6379?auth[]=user&auth[]=password" -~~~ +``` Login to Redis using username, password, and set prefix: -~~~ +```ini session.save_handler = redis session.save_path = "tcp://127.0.0.1:6379?auth[]=user&auth[]=password&prefix=user_PHPREDIS_SESSION:" -~~~ +``` #### Session locking @@ -110,7 +99,7 @@ session.save_path = "tcp://127.0.0.1:6379?auth[]=user&auth[]=password&prefix=use So locking may not work properly in RedisArray or RedisCluster environments. The following INI variables can be used to configure session locking: -~~~ +```ini ; 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. @@ -119,23 +108,23 @@ redis.session.lock_expire = 60 redis.session.lock_wait_time = 50000 ; Maximum number of times to retry (-1 means infinite). Defaults to: 100 redis.session.lock_retries = 2000 -~~~ +``` #### Session compression The following INI variables can be used to configure session compression: -~~~ +```ini ; Should session compression be enabled? Possible values are zstd, lzf, lz4, none. Defaults to: none redis.session.compression = zstd ; What compression level should be used? Compression level depends on used library. For most deployments range 1-9 should be fine. Defaults to: 3 redis.session.compression_level = 3 -~~~ +``` ### 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: -~~~ +```bash # Run tests for Redis class (note this is the default) php tests/TestRedis.php --class Redis @@ -151,18 +140,14 @@ 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. -~~~ +```bash # Just run the 'echo' test php tests/TestRedis.php --class Redis --test echo -~~~ - -## API Documentation - -The [API Documentation](https://phpredis.github.io/phpredis) are a work in progress, but will eventually replace our **ONE README TO RULE THEM ALL** docs. +``` ## Classes and methods @@ -170,7 +155,6 @@ The [API Documentation](https://phpredis.github.io/phpredis) are a work in progr 1. [Class Redis](#class-redis) 1. [Class RedisException](#class-redisexception) -1. [Predefined constants](#predefined-constants) #### Class Redis ----- @@ -205,15 +189,17 @@ $redis = new Redis([ ###### *Parameters* (optional) -*host*: string, the hostname/FQDN/IP address or the path to a unix domain socket; since v5.0.0 it is possible to specify schema -*port*: int, actual port (e.g. `6379`) or `-1` (or `0`) for unix domain socket; setting to < `0` with non-UDS will assume default of `6379` -*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 the value is a string it is used as a persistent ID. Non-strings are cast to boolean. -*auth*: mixed, authentication information -*database*: int, database number -*ssl*: array, SSL context options +| Parameter | Type | Description | +| --- | --- | --- | +| `host` | `string` | the hostname/FQDN/IP address or the path to a unix domain socket; since v5.0.0 it is possible to specify schema | +| `port` | `int` | actual port (e.g. `6379`) or `-1` (or `0`) for unix domain socket; setting to < `0` with non-UDS will assume default of `6379` | +| `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 the value is a string it is used as a persistent ID. Non-strings are cast to boolean. | +| `auth` | `mixed` | authentication information | +| `database` | `int` | database number | +| `ssl` | `array` | SSL context options | #### Class RedisException ----- @@ -221,34 +207,14 @@ phpredis throws a [RedisException](#class-redisexception) object if it can't rea 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](#type) -~~~ -Redis::REDIS_STRING - String -Redis::REDIS_SET - Set -Redis::REDIS_LIST - List -Redis::REDIS_ZSET - Sorted set -Redis::REDIS_HASH - Hash -Redis::REDIS_STREAM - Stream -Redis::REDIS_VECTORSET - Vector set -Redis::REDIS_NOT_FOUND - Not found / other -~~~ - ### Connection 1. [connect, open](#connect-open) - Connect to a server 1. [pconnect, popen](#pconnect-popen) - Connect to a server (persistent) 1. [auth](#auth) - Authenticate to the server -1. [select](#select) - Change the selected database for the current connection -1. [swapdb](#swapdb) - Swaps two Redis databases 1. [close](#close) - Close the connection 1. [setOption](#setoption) - Set client option 1. [getOption](#getoption) - Get client option -1. [ping](#ping) - Ping the server -1. [echo](#echo) - Echo the given string #### connect, open ----- @@ -256,17 +222,22 @@ _**Description**_: Connects to a Redis instance. If phpredis cannot reach the se ###### *Parameters* -*host*: string, *host*: string, the hostname/FQDN/IP address or the path to a unix domain socket; since v5.0.0 it is possible to specify schema -*port*: int, actual port (e.g. `6379`) or `-1` (or `0`) for unix domain socket; setting to < `0` with non-UDS will assume default of `6379`, 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_](https://www.php.net/manual/en/context.ssl.php) configuration. +| Parameter | Type | Description | +| --- | --- | --- | +| `host` | `string` | The Redis server hostname or IP address. | +| `port` | `int` | The Redis server port. Defaults to 6379. | +| `timeout` | `float` | The connection timeout in seconds. Defaults to 0 (no timeout). | +| `persistent_id` | `?string` | If set, a persistent connection will be made with this ID. | +| `retry_interval` | `int` | The number of milliseconds to wait between connection attempts. | +| `read_timeout` | `float` | The read timeout in seconds. Defaults to 0 (no timeout). | +| `context` | `?array` | An optional stream context to use when connecting. See `\Redis::__construct()` for more details. | ###### *Return value* -*BOOL*: `TRUE` on success. Failures typically raise a `RedisException`, though in some edge cases `FALSE` may be returned instead. +| Type | Description | +| --- | --- | +| `bool` | `TRUE` on success. Failures typically raise a `RedisException`, though in some edge cases `FALSE` may be returned instead. | + ###### *Example* @@ -339,16 +310,22 @@ persistent equivalents. ###### *Parameters* -*host*: string, *host*: string, the hostname/FQDN/IP address or the path to a unix domain socket; since v5.0.0 it is possible to specify schema -*port*: int, actual port (e.g. `6379`) or `-1` (or `0`) for unix domain socket; setting to < `0` with non-UDS will assume default of `6379`, 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) +| Parameter | Type | Description | +| --- | --- | --- | +| `host` | `string` | The Redis server hostname. | +| `port` | `int` | The Redis server port. | +| `timeout` | `float` | Connection timeout in seconds. | +| `persistent_id` | `?string` | An optional persistent ID to use for the connection. | +| `retry_interval` | `int` | The number of microseconds to wait before retrying a connection. | +| `read_timeout` | `float` | Read timeout in seconds. | +| `context` | `?array` | An optional stream context array. | ###### *Return value* -*BOOL*: `TRUE` on success, `FALSE` on error. +| Type | Description | +| --- | --- | +| `bool` | `TRUE` on success, `FALSE` on error. | + ###### *Example* @@ -370,12 +347,17 @@ _**Description**_: Authenticate the connection using a password or a username an *Warning*: The password is sent in plain-text over the network. ###### *Parameters* -*MIXED*: password + +| Parameter | Type | Description | +| --- | --- | --- | +| `credentials` | `mixed` | A string password, or an array with one or two string elements. | ###### *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. +| Type | Description | +| --- | --- | +| `Redis\|bool` | `TRUE` if the connection is authenticated, `FALSE` otherwise. In order to authenticate with a username and password you need Redis >= 6.0. | + ###### *Example* ~~~php @@ -393,58 +375,23 @@ $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](#move) - -#### swapdb +#### setOption ----- -_**Description**_: Swap one Redis database with another atomically +_**Description**_: Set client option. ###### *Parameters* -*INTEGER*: db1 -*INTEGER*: db2 - -###### *Return value* -`TRUE` on success and `FALSE` on failure. - -*Note*: Requires Redis >= 4.0.0 - -###### *Example* -~~~php -$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. +| Parameter | Type | Description | +| --- | --- | --- | +| `option` | `int` | The option constant. | +| `value` | `mixed` | The option value. | ###### *Return value* -*BOOL*: `TRUE` on success, `FALSE` on failure. -#### setOption ------ -_**Description**_: Set client option. - -###### *Parameters* -*parameter name* -*parameter value* +| Type | Description | +| --- | --- | +| `bool` | `TRUE` on success, `FALSE` on error. | -###### *Return value* -*BOOL*: `TRUE` on success, `FALSE` on error. ###### *Example* ~~~php @@ -477,15 +424,21 @@ $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NOPREFIX); _**Description**_: Get client option. ###### *Parameters* -*parameter name* + +| Parameter | Type | Description | +| --- | --- | --- | +| `option` | `int` | See command documentation. | ###### *Return value* -Parameter value. + +| Type | Description | +| --- | --- | +| `mixed` | The setting itself or false on failure | + ###### *Example* ~~~php -// return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, -// Redis::SERIALIZER_IGBINARY, Redis::SERIALIZER_MSGPACK or Redis::SERIALIZER_JSON +// Retrieve the current serializer option $redis->getOption(Redis::OPT_SERIALIZER); ~~~ @@ -499,36 +452,18 @@ $redis->ping([string $message]); ~~~ ###### *Return value* -*Mixed*: This method returns `TRUE` on success, or the passed string if called with an argument. - -###### *Example* -~~~php -/* 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* +| Type | Description | +| --- | --- | +| `Redis\|string\|false` | This method returns `TRUE` on success, or the passed string if called with an argument. | -*STRING*: the same message. ### Retry and backoff 1. [Maximum retries](#maximum-retries) 1. [Backoff algorithms](#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_ attempts overall. Defaults to 10. @@ -560,4220 +495,439 @@ $redis->setOption(Redis::OPT_BACKOFF_BASE, 500); // base for backoff computation $redis->setOption(Redis::OPT_BACKOFF_CAP, 750); // backoff time capped at 750ms ~~~ -### Server - -1. [acl](#acl) - Manage Redis ACLs -1. [bgRewriteAOF](#bgrewriteaof) - Asynchronously rewrite the append-only file -1. [bgSave](#bgsave) - Asynchronously save the dataset to disk (in background) -1. [config](#config) - Get or Set the Redis server configuration parameters -1. [dbSize](#dbsize) - Return the number of keys in selected database -1. [flushAll](#flushall) - Remove all keys from all databases -1. [flushDb](#flushdb) - Remove all keys from the current database -1. [info](#info) - Get information and statistics about the server -1. [lastSave](#lastsave) - Get the timestamp of the last disk save -1. [save](#save) - Synchronously save the dataset to disk (wait to complete) -1. [wait](#wait) - Block until write acknowledgements from replicas -1. [waitaof](#waitaof) - Wait for local AOF fsync and replica acknowledgements -1. [slaveOf](#slaveof) - Make the server a slave of another instance, or promote it to master -1. [time](#time) - Return the current server time -1. [slowLog](#slowlog) - Access the Redis slowLog entries - -#### acl +### Transactions + +1. [multi, exec, discard](#multi-exec-discard) - Enter and exit transactional mode +2. [watch, unwatch](#watch-unwatch) - Watches a key for modifications by another client. + +#### multi, exec, discard. ----- -_**Description**_: Execute the Redis ACL command. +_**Description**_: Enter and exit transactional mode. ###### *Parameters* -_variable_: Minimum of one argument for `Redis` and two for `RedisCluster`. - -###### *Example* -~~~php -$redis->acl('USERS'); /* Get a list of users */ -$redis->acl('LOG'); /* See log of Redis' ACL subsystem */ -~~~ -*Note*: In order to use 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](https://redis.io/topics/acl) for an overview of Redis 6 ACLs and [the redis command reference](https://redis.io/commands) for every ACL subcommand. +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `int` | The type of transaction to start. This can either be `Redis::MULTI` or `Redis::PIPELINE'. | -*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](https://redis.io/commands/unlink) command is non-blocking and will perform the actual deletion asynchronously. +Defaults to `Redis::MULTI`. A `Redis::MULTI` block of commands runs as a single transaction; a `Redis::PIPELINE` block is simply transmitted faster to the server, but without any guarantee of atomicity. `discard` cancels a transaction. -#### bgRewriteAOF ------ -_**Description**_: Start the background rewrite of AOF (Append-Only File) +###### *Return value* -###### *Parameters* -None. +| Type | Description | +| --- | --- | +| `Redis\|bool` | `multi()` returns the Redis instance and enters multi-mode. Once in multi-mode, all subsequent method calls return the same object until `exec()` is called. | -###### *Return value* -*BOOL*: `TRUE` in case of success, `FALSE` in case of failure. ###### *Example* ~~~php -$redis->bgRewriteAOF(); +$ret = $redis->multi() + ->set('key1', 'val1') + ->get('key1') + ->set('key2', 'val2') + ->get('key2') + ->exec(); + +/* +$ret == [0 => TRUE, 1 => 'val1', 2 => TRUE, 3 => 'val2']; +*/ ~~~ -#### bgSave +#### watch, unwatch ----- -_**Description**_: Asynchronously save the dataset to disk (in background) +_**Description**_: Watches a key for modifications by another client. + +If the key is modified between `WATCH` and `EXEC`, the MULTI/EXEC transaction will fail (return `FALSE`). `unwatch` cancels all the watching of all keys by this client. ###### *Parameters* -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`. +| Parameter | Type | Description | +| --- | --- | --- | +| `key` | `array\|string` | Either an array with one or more key names, or a string key name | +| `other_keys` | `string` | If the first argument was passed as a string, any number of additional string key names may be passed variadically. | ###### *Example* ~~~php -$redis->bgSave(); +$redis->watch('x'); // or for a list of keys: $redis->watch(['x','another key']); +/* long code here during the execution of which other clients could well modify `x` */ +$ret = $redis->multi() + ->incr('x') + ->exec(); +/* +$ret = FALSE if x has been modified between the call to WATCH and the call to EXEC. +*/ ~~~ -#### config ------ -_**Description**_: Get or Set the Redis server configuration parameters. +### Local Helper Methods -###### *Prototype* -~~~php -$redis->config(string $operation, string|array|null $key = NULL, ?string $value = NULL): mixed; -~~~ +These helpers expose the exact logic PhpRedis uses locally for serialization, compression, and prefixing. -###### *Return value* -*Associative array* for `GET`, key(s) -> value(s) -*bool* for `SET`, `RESETSTAT`, and `REWRITE` +* [getLastError](#getlasterror) - The last error message (if any) +* [clearLastError](#clearlasterror) - Clear the last error message +* [_compress](#_compress) - Compress a string with the configured compression option +* [_uncompress](#_uncompress) - Uncompress a string with the configured compression option +* [_serialize](#_serialize) - Serialize a value with the configured serializer +* [_unserialize](#_unserialize) - Unserialize a string with the configured serializer +* [_pack](#_pack) - Serialize and compress a value exactly as PhpRedis would before sending it to Redis +* [_unpack](#_unpack) - Reverse `_pack` to retrieve the original PHP value +* [_prefix](#_prefix) - Apply the configured key prefix locally +* [_digest](#_digest) - Compute the XXH3 digest of a packed value just like Redis' DIGEST command + +#### getLastError +_**Description**_: Get the last error message, if any. + +###### *Parameters* + +None. + +###### *Return value* +| Type | Description | +| --- | --- | +| `string\|null` | The last error message, or `NULL` if there was no error. | ###### *Examples* ~~~php -$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'); +$redis->del('hash'); +$redis->hmset('hash', ['foo' => 'bar']); +$redis->rpush('hash', 'baz'); +echo $redis->getLastError(); // "ERR Operation against a key holding the wrong kind of value" ~~~ -#### dbSize +#### clearLastError ----- -_**Description**_: Return the number of keys in selected database. +_**Description**_: Clear the last error message ###### *Parameters* + None. ###### *Return value* -*INTEGER*: DB size, in number of keys. -###### *Example* +| Type | Description | +| --- | --- | +| `bool` | This should always return true or throw an exception if we're not connected. | + + +###### *Examples* ~~~php -$count = $redis->dbSize(); -echo "Redis has $count keys\n"; +$redis->set('x', 'a'); +$redis->incr('x'); +$err = $redis->getLastError(); +// "ERR value is not an integer or out of range" +$redis->clearLastError(); +$err = $redis->getLastError(); +// NULL ~~~ -#### flushAll +#### _compress ----- -_**Description**_: Remove all keys from all databases. +_**Description**_: Compress a string using whatever `Redis::OPT_COMPRESSION` is currently set to. This is useful when you need to mimic PhpRedis' compression logic without sending data to Redis. ###### *Parameters* -*async* (bool) requires server version 4.0.0 or greater - -###### *Return value* -*BOOL*: Always `TRUE`. -###### *Example* -~~~php -$redis->flushAll(); -~~~ +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `string` | The value to be compressed | -#### flushDb ------ -_**Description**_: Remove all keys from the current database. +###### *Return value* -###### *Prototype* -~~~php -$redis->flushdb(?bool $sync = NULL): Redis|bool; -~~~ +| Type | Description | +| --- | --- | +| `string` | Returns the compressed string, or the original value if compression is disabled. | -###### *Return value* -*BOOL*: This command returns true on success and false on failure. -###### *Example* +###### *Examples* ~~~php -$redis->flushDb(); +$redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); +$payload = $redis->_compress('large-payload'); ~~~ -#### info +#### _uncompress ----- -_**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](http://redis.io/commands/info)), -which will modify what is returned. +_**Description**_: Reverse `_compress` by uncompressing a string with the compression option currently in use. ###### *Parameters* -*option*: The option to provide redis (e.g. "COMMANDSTATS", "CPU") -###### *Example* -~~~php -$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 */ -~~~ +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `string` | The compressed value to uncompress. | -#### lastSave ------ -_**Description**_: Returns the timestamp of the last disk save. +###### *Return value* -###### *Parameters* -None. +| Type | Description | +| --- | --- | +| `string` | Returns the uncompressed value. Throws an exception if the payload is invalid for the configured compressor. | -###### *Return value* -*INT*: timestamp. -###### *Example* +###### *Examples* ~~~php -$redis->lastSave(); +$redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZ4); +$original = $redis->_uncompress($compressedPayload); ~~~ -#### save +#### _serialize ----- -_**Description**_: Synchronously save the dataset to disk (wait to complete) +_**Description**_: Serialize a value manually using whatever serializer is configured. + +This can be useful for serialization/unserialization of data going in and out of EVAL commands +as phpredis can't automatically do this itself. Note that if no serializer is set, phpredis +will change Array values to 'Array', and Objects to 'Object'. ###### *Parameters* -None. + +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `mixed` | The value to serialize | ###### *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* +| Type | Description | +| --- | --- | +| `string` | The serialized representation of the value. | + + +###### *Examples* ~~~php -$redis->save(); +$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); +$redis->_serialize("foo"); // returns "foo" +$redis->_serialize([]); // Returns "Array" +$redis->_serialize(new stdClass()); // Returns "Object" + +$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); +$redis->_serialize("foo"); // Returns 's:3:"foo";' ~~~ -#### wait +#### _unserialize ----- -_**Description**_: Block the client until a specified number of replicas acknowledge the most recent write or until the timeout elapses. +_**Description**_: Unserialize a string using whatever serializer is configured. + +If there is no serializer set, the value will be returned unchanged. If there is a serializer set up, +and the data passed in is malformed, an exception will be thrown. ###### *Parameters* -*numreplicas* (int): The number of replicas that must confirm the write. -*timeout* (int): Maximum time to wait in milliseconds (`0` to wait indefinitely). + +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `string` | The value to unserialize | ###### *Return value* -*INT*: The number of replicas that acknowledged the write before timing out, or `FALSE` on error. -###### *Example* -~~~php -$redis->set('user:1', 'marco'); -$confirmed = $redis->wait(1, 500); +| Type | Description | +| --- | --- | +| `mixed` | The PHP value represented by the serialized string. | -if ($confirmed < 1) { - // Handle the case where the write was not replicated in time. -} + +###### *Examples* +~~~php +$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); +$redis->_unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // Will return [1,2,3] ~~~ -#### waitaof +#### _pack ----- -_**Description**_: Block until Redis has durably written recent changes to the local AOF file the requested number of times and received acknowledgements from the requested number of replicas (Redis >= 7.2). +_**Description**_: Pack a value the same way PhpRedis does internally by first serializing (if configured) and then compressing (if configured). This mirrors the exact bytes Redis receives. ###### *Parameters* -*numlocal* (int): Minimum number of local AOF fsync operations to wait for. -*numreplicas* (int): Number of replicas that must acknowledge the write. -*timeout* (int): Maximum time to wait in milliseconds (`0` to wait indefinitely). + +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `mixed` | The value to pack | ###### *Return value* -*ARRAY*: Two integers, where element `0` is the number of local fsync operations performed and element `1` is the number of replica acknowledgements, or `FALSE` on error. -###### *Example* -~~~php -[$local, $replicas] = $redis->waitaof(1, 1, 1000); +| Type | Description | +| --- | --- | +| `string` | The packed payload that would be sent to Redis. | -if ($local < 1 || $replicas < 1) { - // The write was not persisted or replicated as requested. -} + +###### *Examples* +~~~php +$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); +$redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); +$payload = $redis->_pack(['a' => 1]); ~~~ -#### slaveOf +#### _unpack ----- -_**Description**_: Changes the slave status +_**Description**_: Reverse `_pack` by uncompressing and then unserializing a payload using the current PhpRedis options. ###### *Parameters* -Either host (string) and port (int), or no parameter to stop being a slave. + +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `string` | The value which has been serialized and compressed. | ###### *Return value* -*BOOL*: `TRUE` in case of success, `FALSE` in case of failure. -###### *Example* +| Type | Description | +| --- | --- | +| `mixed` | The unpacked PHP value. | + + +###### *Examples* ~~~php -$redis->slaveOf('10.0.1.7', 6379); -/* ... */ -$redis->slaveOf(); +$value = $redis->_unpack($payload); ~~~ -#### time +#### _prefix ----- -_**Description**_: Return the current server time. +_**Description**_: A utility method to prefix the value with the prefix setting for PhpRedis. ###### *Parameters* -(none) + +| Parameter | Type | Description | +| --- | --- | --- | +| `key` | `string` | The key/string to prefix | ###### *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. + +| Type | Description | +| --- | --- | +| `string` | Returns the prefixed value when a prefix is configured, or the original string otherwise. | + ###### *Examples* ~~~php -$redis->time(); +$redis->setOption(Redis::OPT_PREFIX, 'my-prefix:'); +$redis->_prefix('my-value'); // Will return 'my-prefix:my-value' ~~~ -#### slowLog +#### _digest ----- -_**Description**_: Access the Redis slowLog +_**Description**_: Compute the XXH3 digest of a PHP value after it has been `_pack`ed. This produces the same output as Redis' `DIGEST` command, making it easy to verify values locally. ###### *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. -##### + +| Parameter | Type | Description | +| --- | --- | --- | +| `value` | `mixed` | The value to compute the digest for. | ###### *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* -~~~php -// Get ten slowLog entries -$redis->slowLog('get', 10); -// Get the default number of slowLog entries +| Type | Description | +| --- | --- | +| `string` | A 16 character hex string containing the XXH3 digest. | -$redis->slowLog('get'); -// Reset our slowLog -$redis->slowLog('reset'); -// Retrieve slowLog length -$redis->slowLog('len'); +###### *Examples* +~~~php +$digest = $redis->_digest(['foo' => 'bar']); ~~~ -### Keys and Strings +### Introspection -#### Strings ------ +1. [isConnected](#isconnected) - Check if PhpRedis believes it is connected +1. [getHost](#gethost) - Retrieve the configured host or unix socket +1. [getPort](#getport) - Retrieve the configured port +1. [getDbNum](#getdbnum) - Get the currently selected database number +1. [getTimeout](#gettimeout) - Get the write timeout value +1. [getReadTimeout](#getreadtimeout) - Get the configured read timeout +1. [getPersistentID](#getpersistentid) - Get the persistent ID for the connection +1. [getAuth](#getauth) - Retrieve authentication credentials in use -* [append](#append) - Append a value to a key -* [bitCount](#bitcount) - Count set bits in a string -* [bitOp](#bitop) - Perform bitwise operations between strings -* [decr, decrBy](#decr-decrby) - Decrement the value of a key -* [get](#get) - Get the value of a key -* [getEx](#getex) - Get the value of a key and set its expiration -* [getBit](#getbit) - Returns the bit value at offset in the string value stored at key -* [getRange](#getrange) - Get a substring of the string stored at a key -* [getSet](#getset) - Set the string value of a key and return its old value -* [incr, incrBy](#incr-incrby) - Increment the value of a key -* [incrByFloat](#incrbyfloat) - Increment the float value of a key by the given amount -* [mGet](#mget) - Get the values of all the given keys -* [mSet, mSetNX](#mset-msetnx) - Set multiple keys to multiple values -* [set](#set) - Set the string value of a key -* [setBit](#setbit) - Sets or clears the bit at offset in the string value stored at key -* [setEx, pSetEx](#setex-psetex) - Set the value and expiration of a key -* [setNx](#setnx) - Set the value of a key, only if the key does not exist -* [setRange](#setrange) - Overwrite part of a string at key starting at the specified offset -* [strLen](#strlen) - Get the length of the value stored in a key - -#### Keys ------ - -* [del, delete, unlink](#del-delete-unlink) - Delete a key -* [dump](#dump) - Return a serialized version of the value stored at the specified key. -* [exists](#exists) - Determine if a key exists -* [expire, pexpire](#expire-pexpire) - Set a key's time to live in seconds -* [expireAt, pexpireAt](#expireat-pexpireat) - Set the expiration for a key as a UNIX timestamp -* [keys](#keys-1) - Find all keys matching the given pattern -* [scan](#scan) - Scan for keys in the keyspace (Redis >= 2.8.0) -* [migrate](#migrate) - Atomically transfer a key from a Redis instance to another one -* [move](#move) - Move a key to another database -* [object](#object) - Inspect the internals of Redis objects -* [persist](#persist) - Remove the expiration from a key -* [randomKey](#randomkey) - Return a random key from the keyspace -* [rename](#rename) - Rename a key -* [renameNx](#renamenx) - Rename a key, only if the new key does not exist -* [type](#type) - Determine the type stored at key -* [sort](#sort) - Sort the elements in a list, set or sorted set -* [ttl, pttl](#ttl-pttl) - Get the time to live for a key -* [restore](#restore) - Create a key using the provided serialized value, previously obtained with [dump](#dump). - ------ - -#### get ------ -_**Description**_: Get the value related to the specified key - -###### *Parameters* -*key* - -###### *Return value* -*String* or *Bool*: If key doesn't exist, `FALSE` is returned. Otherwise, the value related to this key is returned. - -###### *Examples* - -~~~php -$redis->get('key'); -~~~ - -#### getEx ------ -_**Description**_: Get the value related to the specified key and set its expiration - -###### *Parameters* -*key* -*options array* (optional) with the following keys: - * `EX` - expire time in seconds - * `PX` - expire time in milliseconds - * `EXAT` - expire time in seconds since UNIX epoch - * `PXAT` - expire time in milliseconds since UNIX epoch - * `PERSIST` - remove the expiration from the key - -###### *Return value* -*String* or *Bool*: If key doesn't exist, `FALSE` is returned. Otherwise, the value related to this key is returned. - -###### *Examples* - -~~~php -$redis->getEx('key', ['EX' => 10]); // get key and set its expiration to 10 seconds -~~~ - -#### 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* -~~~php -// 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, `FALSE` in case of failure. - -###### *Examples* - -~~~php -$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` if the command is successful, `FALSE` in case of failure. - -###### *Examples* -~~~php -$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](https://redis.io/commands/unlink) command is non-blocking and will perform the actual deletion asynchronously. - -###### *Return value* -*Long* Number of keys deleted (`0` if none existed to start with), `FALSE` in case of unexpected failure (i.e. connection, etc.) - -###### *Examples* -~~~php -$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* Number of keys tested that exist (`0` if none do), `FALSE` in case of failure. - -###### *Examples* -~~~php -$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 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* -~~~php -$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* -~~~php -$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 ------ -_**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* -~~~php -$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`]; -~~~ - -#### 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* -~~~php -$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* -~~~php -$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* - -~~~php -$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 ------ -_**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* -~~~php -$redis->set('x', '42'); -$redis->rename('x', 'y'); -$redis->get('y'); // → 42 -$redis->get('x'); // → `FALSE` -~~~ - -#### 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* -~~~php -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* -~~~php -$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. -~~~ - -#### expireAt, pexpireAt ------ -_**Description**_: Set a specific timestamp for a key to expire in seconds or milliseconds. - -###### *Prototype* -~~~php -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 of an error. You can detect an actual error by checking `getLastError()`. - -###### *Example* -~~~php -$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 ------ -_**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* -~~~php -$allKeys = $redis->keys('*'); // all keys will match this. -$keyWithUserPrefix = $redis->keys('user*'); -~~~ - -#### 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 returns zero keys - -*Note*: SCAN is a "directed node" command in [RedisCluster](cluster.md#directed-node-commands) - -###### *Example* -~~~php - -/* 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* -~~~php -$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* -~~~php -$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* -~~~php -$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* -~~~php -$redis->set('key', 'string value'); -$redis->getRange('key', 0, 5); /* 'string' */ -$redis->getRange('key', -5, -1); /* 'value' */ -~~~ - -#### 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* -~~~php -$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* -~~~php -$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* -~~~php -$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* -~~~php -$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* -~~~php -$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* -~~~php -$redis->ttl('key'); -~~~ - -#### persist ------ -_**Description**_: Remove the expiration timer from a key. - -###### *Parameters* -*Key*: key - -###### *Return value* -*BOOL*: `TRUE` if a timeout was removed, `FALSE` if the key didn’t exist or didn’t have an expiration timer. - -###### *Example* -~~~php -$redis->persist('key'); -~~~ - -#### mSet, mSetNx ------ -_**Description**_: Sets multiple key-value pairs in one atomic command. MSETNX only returns TRUE if all the keys were set (see SETNX). - -###### *Parameters* -*Pairs*: [key => value, ...] - -###### *Return value* -*Bool* `TRUE` in case of success, `FALSE` in case of failure. - -###### *Example* -~~~php - -$redis->mSet(['key0' => 'value0', 'key1' => 'value1']); -var_dump($redis->get('key0')); -var_dump($redis->get('key1')); - -~~~ -Output: -~~~ -string(6) "value0" -string(6) "value1" -~~~ - - - -#### dump ------ -_**Description**_: Dump a key out of a redis database, the value of which can later be passed into redis using the RESTORE command. The data -that comes out of DUMP is a binary representation of the key as Redis stores it. -###### *Parameters* -*key* string -###### *Return value* -The Redis encoded value of the key, or FALSE if the key doesn't exist -###### *Examples* -~~~php -$redis->set('foo', 'bar'); -$val = $redis->dump('foo'); // $val will be the Redis encoded key value -~~~ - -#### restore ------ -_**Description**_: Restore a key from the result of a DUMP operation. -###### *Parameters* -*key* string. The key name -*ttl* integer. How long the key should live (if zero, no expire will be set on the key) -*value* string (binary). The Redis encoded key value (from DUMP) -###### *Examples* -~~~php -$redis->set('foo', 'bar'); -$val = $redis->dump('foo'); -$redis->restore('bar', 0, $val); // The key 'bar', will now be equal to the key 'foo' -~~~ - -#### migrate ------ -_**Description**_: Migrates a key to a different Redis instance. - -**Note:**: Redis introduced migrating multiple keys in 3.0.6, so you must have at least -that version to call `migrate` with an array of keys. - -###### *Parameters* -*host* string. The destination host -*port* integer. The TCP port to connect to. -*key(s)* string or array. -*destination-db* integer. The target DB. -*timeout* integer. The maximum amount of time given to this transfer. -*copy* boolean, optional. Should we send the COPY flag to redis. -*replace* boolean, optional. Should we send the REPLACE flag to redis -###### *Examples* -~~~php -$redis->migrate('backup', 6379, 'foo', 0, 3600); -$redis->migrate('backup', 6379, 'foo', 0, 3600, true, true); /* copy and replace */ -$redis->migrate('backup', 6379, 'foo', 0, 3600, false, true); /* just REPLACE flag */ - -/* Migrate multiple keys (requires Redis >= 3.0.6) -$redis->migrate('backup', 6379, ['key1', 'key2', 'key3'], 0, 3600); -~~~ - - - -### Hashes - -* [hDel](#hdel) - Delete one or more hash fields -* [hExists](#hexists) - Determine if a hash field exists -* [hGet](#hget) - Get the value of a hash field -* [hGetAll](#hgetall) - Get all the fields and values in a hash -* [hIncrBy](#hincrby) - Increment the integer value of a hash field by the given number -* [hIncrByFloat](#hincrbyfloat) - Increment the float value of a hash field by the given amount -* [hKeys](#hkeys) - Get all the fields in a hash -* [hLen](#hlen) - Get the number of fields in a hash -* [hMGet](#hmget) - Get the values of all the given hash fields -* [hMSet](#hmset) - Set multiple hash fields to multiple values -* [hSet](#hset) - Set the string value of a hash field -* [hSetNx](#hsetnx) - Set the value of a hash field, only if the field does not exist -* [hVals](#hvals) - Get all the values in a hash -* [hScan](#hscan) - Scan a hash key for members -* [hStrLen](#hstrlen) - Get the string length of the value associated with field in the hash - -#### hSet ------ -_**Description**_: Adds a value to the hash stored at key. -###### *Parameters* -*key* -*hashKey* -*value* - -###### *Return value* -*LONG* `1` if value didn't exist and was added successfully, `0` if the value was already present and was replaced, `FALSE` if there was an error. -###### *Example* -~~~php -$redis->del('h') -$redis->hSet('h', 'key1', 'hello'); /* 1, 'key1' => 'hello' in the hash at "h" */ -$redis->hGet('h', 'key1'); /* returns "hello" */ - -$redis->hSet('h', 'key1', 'plop'); /* 0, value was replaced. */ -$redis->hGet('h', 'key1'); /* returns "plop" */ -~~~ - -#### hSetNx ------ -_**Description**_: Adds a value to the hash stored at key only if this field isn't already in the hash. - -###### *Return value* -*BOOL* `TRUE` if the field was set, `FALSE` if it was already present. - -###### *Example* -~~~php -$redis->del('h') -$redis->hSetNx('h', 'key1', 'hello'); /* TRUE, 'key1' => 'hello' in the hash at "h" */ -$redis->hSetNx('h', 'key1', 'world'); /* FALSE, 'key1' => 'hello' in the hash at "h". No change since the field wasn't replaced. */ -~~~ - - -#### hGet ------ -_**Description**_: Gets a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, `FALSE` is returned. -###### *Parameters* -*key* -*hashKey* - -###### *Return value* -*STRING* The value, if the command executed successfully -*BOOL* `FALSE` in case of failure - - -#### hLen ------ -_**Description**_: Returns the length of a hash, in number of items -###### *Parameters* -*key* - -###### *Return value* -*LONG* the number of items in a hash, `FALSE` if the key doesn't exist or isn't a hash. -###### *Example* -~~~php -$redis->del('h') -$redis->hSet('h', 'key1', 'hello'); -$redis->hSet('h', 'key2', 'plop'); -$redis->hLen('h'); /* returns 2 */ -~~~ - -#### hDel ------ -_**Description**_: Removes a value from the hash stored at key. If the hash table doesn't exist, or the key doesn't exist, `FALSE` is returned. -###### *Parameters* -*key* -*hashKey1* -*hashKey2* -... - -###### *Return value* -*LONG* the number of deleted keys, 0 if the key doesn't exist, `FALSE` if the key isn't a hash. - - -#### hKeys ------ -_**Description**_: Returns the keys in a hash, as an array of strings. - -###### *Parameters* -*Key*: key - -###### *Return value* -An array of elements, the keys of the hash. This works like PHP's array_keys(). - -###### *Example* -~~~php -$redis->del('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. - -#### hVals ------ -_**Description**_: Returns the values in a hash, as an array of strings. - -###### *Parameters* -*Key*: key - -###### *Return value* -An array of elements, the values of the hash. This works like PHP's array_values(). - -###### *Example* -~~~php -$redis->del('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. - -#### hGetAll ------ -_**Description**_: Returns the whole hash, as an array of strings indexed by strings. - -###### *Parameters* -*Key*: key - -###### *Return value* -An array of elements, the contents of the hash. - -###### *Example* -~~~php -$redis->del('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. - -#### hExists ------ -_**Description**_: Verify if the specified member exists in a key. -###### *Parameters* -*key* -*memberKey* -###### *Return value* -*BOOL*: If the member exists in the hash table, return `TRUE`, otherwise return `FALSE`. -###### *Examples* -~~~php -$redis->hSet('h', 'a', 'x'); -$redis->hExists('h', 'a'); /* TRUE */ -$redis->hExists('h', 'NonExistingKey'); /* FALSE */ -~~~ - -#### hIncrBy ------ -_**Description**_: Increments the value of a member from a hash by a given amount. -###### *Parameters* -*key* -*member* -*value*: (integer) value that will be added to the member's value -###### *Return value* -*LONG* the new value -###### *Examples* -~~~php -$redis->del('h'); -$redis->hIncrBy('h', 'x', 2); /* returns 2: h[x] = 2 now. */ -$redis->hIncrBy('h', 'x', 1); /* h[x] ← 2 + 1. Returns 3 */ -~~~ - -#### hIncrByFloat ------ -_**Description**_: Increments the value of a hash member by the provided float value -###### *Parameters* -*key* -*member* -*value*: (float) value that will be added to the member's value -###### *Return value* -*FLOAT* the new value -###### *Examples* -~~~php -$redis->del('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 */ -~~~ - -#### hMSet ------ -_**Description**_: Fills in a whole hash. Non-string values are converted to string, using the standard `(string)` cast. NULL values are stored as empty strings. -###### *Parameters* -*key* -*members*: key → value array -###### *Return value* -*BOOL* -###### *Examples* -~~~php -$redis->del('user:1'); -$redis->hMSet('user:1', ['name' => 'Joe', 'salary' => 2000]); -$redis->hIncrBy('user:1', 'salary', 100); // Joe earns 100 more now. -~~~ - -#### hMGet ------ -_**Description**_: Retrieve the values associated to the specified fields in the hash. -###### *Parameters* -*key* -*memberKeys* Array -###### *Return value* -*Array* An array of elements, the values of the specified fields in the hash, with the hash keys as array keys. -###### *Examples* -~~~php -$redis->del('h'); -$redis->hSet('h', 'field1', 'value1'); -$redis->hSet('h', 'field2', 'value2'); -$redis->hMGet('h', ['field1', 'field2']); /* returns ['field1' => 'value1', 'field2' => 'value2'] */ -~~~ - -#### hScan ------ -_**Description**_: Scan a HASH value for members, with an optional pattern and count -###### *Parameters* -*key*: String -*iterator*: Long (reference) -*pattern*: Optional pattern to match against -*count*: How many keys to return in a go (only a suggestion to Redis) -###### *Return value* -*Array* An array of members that match our pattern - -###### *Examples* -~~~php -$it = NULL; -/* Don't ever return an empty array until we're done iterating */ -$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); -while($arr_keys = $redis->hScan('hash', $it)) { - foreach($arr_keys as $str_field => $str_value) { - echo "$str_field => $str_value\n"; /* Print the hash member and value */ - } -} -~~~ - -#### hStrLen ------ -_**Description**_: Get the string length of the value associated with field in the hash stored at key. -###### *Parameters* -*key*: String -*field*: String -###### *Return value* -*LONG* the string length of the value associated with field, or zero when field is not present in the hash or key does not exist at all. - -### Lists - -* [blPop, brPop](#blpop-brpop) - Remove and get the first/last element in a list -* [bRPopLPush](#brpoplpush) - Pop a value from a list, push it to another list and return it -* [lIndex](#lindex) - Get an element from a list by its index -* [lInsert](#linsert) - Insert an element before or after another element in a list -* [lLen](#llen) - Get the length/size of a list -* [lPop](#lpop) - Remove and get the first element in a list -* [lPush](#lpush) - Prepend one or multiple values to a list -* [lPushx](#lpushx) - Prepend a value to a list, only if the list exists -* [lRange](#lrange) - Get a range of elements from a list -* [lRem](#lrem) - Remove elements from a list -* [lSet](#lset) - Set the value of an element in a list by its index -* [lTrim](#ltrim) - Trim a list to the specified range -* [rPop](#rpop) - Remove and get the last element in a list -* [rPopLPush](#rpoplpush) - Remove the last element in a list, append it to another list and return it (redis >= 1.1) -* [rPush](#rpush) - Append one or multiple values to a list -* [rPushX](#rpushx) - Append a value to a list, only if the list exists - -#### blPop, brPop ------ -_**Description**_: Is a blocking lPop(rPop) primitive. If at least one of the lists contains at least one element, the element will be popped from the head of the list and returned to the caller. -If all the list identified by the keys passed in arguments are empty, blPop will block during the specified timeout until an element is pushed to one of those lists. This element will be popped. - -###### *Parameters* -*ARRAY* Array containing the keys of the lists -*INTEGER* Timeout -Or -*STRING* Key1 -*STRING* Key2 -*STRING* Key3 -... -*STRING* Keyn -*INTEGER* Timeout - -###### *Return value* -*ARRAY* ['listName', 'element'] - -###### *Example* -~~~php -/* Non blocking feature */ -$redis->lPush('key1', 'A'); -$redis->del('key2'); - -$redis->blPop('key1', 'key2', 10); /* ['key1', 'A'] */ -/* OR */ -$redis->blPop(['key1', 'key2'], 10); /* ['key1', 'A'] */ - -$redis->brPop('key1', 'key2', 10); /* ['key1', 'A'] */ -/* OR */ -$redis->brPop(['key1', 'key2'], 10); /* ['key1', 'A'] */ - -/* Blocking feature */ - -/* process 1 */ -$redis->del('key1'); -$redis->blPop('key1', 10); -/* blocking for 10 seconds */ - -/* process 2 */ -$redis->lPush('key1', 'A'); - -/* process 1 */ -/* ['key1', 'A'] is returned*/ -~~~ - -#### bRPopLPush ------ -_**Description**_: A blocking version of `rPopLPush`, with an integral timeout in the third parameter. - -###### *Parameters* -*Key*: srckey -*Key*: dstkey -*Long*: timeout - -###### *Return value* -*STRING* The element that was moved in case of success, `FALSE` in case of timeout. - -#### lIndex ------ -_**Description**_: Return the specified element of the list stored at the specified key. - -0 the first element, 1 the second ... --1 the last element, -2 the penultimate ... - -Return `FALSE` in case of a bad index or a key that doesn't point to a list. - -###### *Parameters* -*key* -*index* - -###### *Return value* -*String* the element at this index -*Bool* `FALSE` if the key identifies a non-string data type, or no value corresponds to this index in the list `Key`. - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ -$redis->lindex('key1', 0); /* 'A' */ -$redis->lindex('key1', -1); /* 'C' */ -$redis->lindex('key1', 10); /* `FALSE` */ -~~~ - -#### lInsert ------ -_**Description**_: Insert value in the list before or after the pivot value. - -The parameter options specify the position of the insert (before or after). -If the list didn't exists, or the pivot didn't exists, the value is not inserted. - -###### *Parameters* -*key* -*position* Redis::BEFORE | Redis::AFTER -*pivot* -*value* - -###### *Return value* -The number of the elements in the list, -1 if the pivot didn't exists. - -###### *Example* -~~~php -$redis->del('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); /* ['A', 'B', 'X', 'C'] */ - -$redis->lInsert('key1', Redis::AFTER, 'C', 'Y'); /* 5 */ -$redis->lRange('key1', 0, -1); /* ['A', 'B', 'X', 'C', 'Y'] */ - -$redis->lInsert('key1', Redis::AFTER, 'W', 'value'); /* -1 */ -~~~ - -#### lPop ------ -_**Description**_: Return and remove the first element of the list. - -###### *Parameters* -*key* - -###### *Return value* -*STRING* if command executed successfully -*BOOL* `FALSE` in case of failure (empty list) - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ -$redis->lPop('key1'); /* key1 => [ 'B', 'C' ] */ -~~~ - -#### lPush ------ -_**Description**_: Adds one or more values to the head of a LIST. Creates the list if the key didn't exist. If the key exists and is not a list, `FALSE` is returned. - -###### *Prototype* -~~~php -$redis->lPush($key, $entry [, $entry, $entry]); -~~~ - -###### *Return value* -*LONG* The new length of the list in case of success, `FALSE` in case of Failure. - -###### *Examples* -~~~php -$redis->del('key1'); -$redis->lPush('key1', 'F'); // returns 1 -$redis->lPush('key1', 'E'); // returns 2 -$redis->lPush('key1', 'D'); // returns 3 -/* key1 now contains: [ 'D', 'E', 'F' ] */ - -$redis->lPush('key1', 'C', 'B', 'A'); // Returns 6 -/* key1 now contains: [ 'A', 'B', 'C', 'D', 'E', 'F' ] -~~~ - -#### lPushx ------ -_**Description**_: Adds the string value to the head (left) of the list if the list exists. - -###### *Parameters* -*key* -*value* String, value to push in key - -###### *Return value* -*LONG* The new length of the list in case of success, `FALSE` in case of Failure. - -###### *Examples* -~~~php -$redis->del('key1'); -$redis->lPushx('key1', 'A'); // returns 0 -$redis->lPush('key1', 'A'); // returns 1 -$redis->lPushx('key1', 'B'); // returns 2 -$redis->lPushx('key1', 'C'); // returns 3 -/* key1 now points to the following list: [ 'A', 'B', 'C' ] */ -~~~ - -#### lRange ------ -_**Description**_: Returns the specified elements of the list stored at the specified key in the range [start, end]. start and stop are interpreted as indices: -0 the first element, 1 the second ... --1 the last element, -2 the penultimate ... - -###### *Parameters* -*key* -*start* -*end* - -###### *Return value* -*Array* containing the values in specified range. - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); -$redis->lRange('key1', 0, -1); /* ['A', 'B', 'C'] */ -~~~ - -#### lRem ------ -_**Description**_: Removes the first `count` occurrences of the value element from the list. If count is zero, all the matching elements are removed. If count is negative, elements are removed from tail to head. - -**Note**: The argument order is not the same as in the Redis documentation. This difference is kept for compatibility reasons. - -###### *Parameters* -*key* -*value* -*count* - -###### *Return value* -*LONG* the number of elements to remove -*BOOL* `FALSE` if the value identified by key is not a list. - -###### *Example* -~~~php -$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); /* ['A', 'A', 'C', 'B', 'A'] */ -$redis->lRem('key1', 'A', 2); /* 2 */ -$redis->lRange('key1', 0, -1); /* ['C', 'B', 'A'] */ -~~~ - -#### lSet ------ -_**Description**_: Set the list at index with the new value. - -###### *Parameters* -*key* -*index* -*value* - -###### *Return value* -*BOOL* `TRUE` if the new value was set. `FALSE` if the index is out of range, or data type identified by key is not a list. - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ -$redis->lindex('key1', 0); /* 'A' */ -$redis->lSet('key1', 0, 'X'); -$redis->lindex('key1', 0); /* 'X' */ -~~~ - -#### lTrim ------ -_**Description**_: Trims an existing list so that it will contain only a specified range of elements. - -###### *Parameters* -*key* -*start* -*stop* - -###### *Return value* -*Array* -*Bool* return `FALSE` if the key identify a non-list value. - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); -$redis->lRange('key1', 0, -1); /* ['A', 'B', 'C'] */ -$redis->lTrim('key1', 0, 1); -$redis->lRange('key1', 0, -1); /* ['A', 'B'] */ -~~~ - -#### rPop ------ -_**Description**_: Returns and removes the last element of the list. - -###### *Parameters* -*key* - -###### *Return value* -*STRING* if command executed successfully -*BOOL* `FALSE` in case of failure (empty list) - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ -$redis->rPop('key1'); /* key1 => [ 'A', 'B' ] */ -~~~ - -#### rPopLPush ------ -_**Description**_: Pops a value from the tail of a list, and pushes it to the front of another list. Also return this value. (redis >= 1.1) - -###### *Parameters* -*Key*: srckey -*Key*: dstkey - -###### *Return value* -*STRING* The element that was moved in case of success, `FALSE` in case of failure. - -###### *Example* -~~~php -$redis->del('x', 'y'); - -$redis->lPush('x', 'abc'); -$redis->lPush('x', 'def'); -$redis->lPush('y', '123'); -$redis->lPush('y', '456'); - -// move the last of x to the front of y. -var_dump($redis->rPopLPush('x', 'y')); -var_dump($redis->lRange('x', 0, -1)); -var_dump($redis->lRange('y', 0, -1)); - -~~~ -Output: -~~~ -string(3) "abc" -array(1) { - [0]=> - string(3) "def" -} -array(3) { - [0]=> - string(3) "abc" - [1]=> - string(3) "456" - [2]=> - string(3) "123" -} -~~~ - -#### rPush ------ -_**Description**_: Adds one or more entries to the tail of a LIST. Redis will create the list if it doesn't exist. - -###### *Prototype* -~~~php -$redis->rPush($key, $entry [, $entry, $entry]); -~~~ - -###### *Return value* -*LONG* The new length of the list in case of success, `FALSE` in case of Failure. - -###### *Examples* -~~~php -$redis->del('key1'); -$redis->rPush('key1', 'A'); // returns 1 -$redis->rPush('key1', 'B'); // returns 2 -$redis->rPush('key1', 'C'); // returns 3 -$redis->rPush('key1', 'D', 'E', 'F'); // returns 6 -/* key1 now contains: [ 'A', 'B', 'C', 'D', 'E', 'F' ] */ -~~~ - -#### rPushX ------ -_**Description**_: Adds the string value to the tail (right) of the list if the list exists. `FALSE` in case of Failure. - -###### *Parameters* -*key* -*value* String, value to push in key - -###### *Return value* -*LONG* The new length of the list in case of success, `FALSE` in case of Failure. - -###### *Examples* -~~~php -$redis->del('key1'); -$redis->rPushX('key1', 'A'); // returns 0 -$redis->rPush('key1', 'A'); // returns 1 -$redis->rPushX('key1', 'B'); // returns 2 -$redis->rPushX('key1', 'C'); // returns 3 -/* key1 now points to the following list: [ 'A', 'B', 'C' ] */ -~~~ - -#### lLen ------ -_**Description**_: Returns the size of a list identified by Key. - -If the list didn't exist or is empty, the command returns 0. If the data type identified by Key is not a list, the command return `FALSE`. - -###### *Parameters* -*Key* - -###### *Return value* -*LONG* The size of the list identified by Key exists. -*BOOL* `FALSE` if the data type identified by Key is not list - -###### *Example* -~~~php -$redis->rPush('key1', 'A'); -$redis->rPush('key1', 'B'); -$redis->rPush('key1', 'C'); /* key1 => [ 'A', 'B', 'C' ] */ -$redis->lLen('key1');/* 3 */ -$redis->rPop('key1'); -$redis->lLen('key1');/* 2 */ -~~~ - - -### Sets - -* [sAdd](#sadd) - Add one or more members to a set -* [sCard](#scard) - Get the number of members in a set -* [sDiff](#sdiff) - Subtract multiple sets -* [sDiffStore](#sdiffstore) - Subtract multiple sets and store the resulting set in a key -* [sInter](#sinter) - Intersect multiple sets -* [sInterStore](#sinterstore) - Intersect multiple sets and store the resulting set in a key -* [sIsMember](#sismember) - Determine if a given value is a member of a set -* [sMembers](#smembers) - Get all the members in a set -* [sMove](#smove) - Move a member from one set to another -* [sPop](#spop) - Remove and return one or more members of a set at random -* [sRandMember](#srandmember) - Get one or multiple random members from a set -* [sRem](#srem) - Remove one or more members from a set -* [sUnion](#sunion) - Add multiple sets -* [sUnionStore](#sunionstore) - Add multiple sets and store the resulting set in a key -* [sScan](#sscan) - Scan a set for members - -#### sAdd ------ -_**Description**_: Adds a value to the set value stored at key. -###### *Parameters* -*key* -*value* - -###### *Return value* -*LONG* the number of elements added to the set. -###### *Example* -~~~php -$redis->sAdd('key1' , 'member1'); /* 1, 'key1' => {'member1'} */ -$redis->sAdd('key1' , 'member2', 'member3'); /* 2, 'key1' => {'member1', 'member2', 'member3'}*/ -$redis->sAdd('key1' , 'member2'); /* 0, 'key1' => {'member1', 'member2', 'member3'}*/ -~~~ - -#### sCard ------ -_**Description**_: Returns the cardinality of the set identified by key. -###### *Parameters* -*key* -###### *Return value* -*LONG* the cardinality of the set identified by key, 0 if the set doesn't exist. -###### *Example* -~~~php -$redis->sAdd('key1' , 'member1'); -$redis->sAdd('key1' , 'member2'); -$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/ -$redis->sCard('key1'); /* 3 */ -$redis->sCard('keyX'); /* 0 */ -~~~ - -#### sDiff ------ -_**Description**_: Performs the difference between N sets and returns it. - -###### *Parameters* -*Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis. - -###### *Return value* -*Array of strings*: The difference of the first set will all the others. - -###### *Example* -~~~php -$redis->del('s0', 's1', 's2'); - -$redis->sAdd('s0', '1'); -$redis->sAdd('s0', '2'); -$redis->sAdd('s0', '3'); -$redis->sAdd('s0', '4'); - -$redis->sAdd('s1', '1'); -$redis->sAdd('s2', '3'); - -var_dump($redis->sDiff('s0', 's1', 's2')); -~~~ -Return value: all elements of s0 that are neither in s1 nor in s2. -~~~ -array(2) { - [0]=> - string(1) "4" - [1]=> - string(1) "2" -} -~~~ - -#### sDiffStore ------ -_**Description**_: Performs the same action as sDiff, but stores the result in the first key -###### *Parameters* -*Key*: dstkey, the key to store the diff into. - -*Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis -###### *Return value* -*INTEGER*: The cardinality of the resulting set, or `FALSE` in case of a missing key. - -###### *Example* -~~~php -$redis->del('s0', 's1', 's2'); - -$redis->sAdd('s0', '1'); -$redis->sAdd('s0', '2'); -$redis->sAdd('s0', '3'); -$redis->sAdd('s0', '4'); - -$redis->sAdd('s1', '1'); -$redis->sAdd('s2', '3'); - -var_dump($redis->sDiffStore('dst', 's0', 's1', 's2')); -var_dump($redis->sMembers('dst')); -~~~ -Return value: the number of elements of s0 that are neither in s1 nor in s2. -~~~ -int(2) -array(2) { - [0]=> - string(1) "4" - [1]=> - string(1) "2" -} -~~~ - -#### sInter ------ -_**Description**_: Returns the members of a set resulting from the intersection of all the sets held at the specified keys. - -If just a single key is specified, then this command produces the members of this set. If one of the keys -is missing, `FALSE` is returned. - -###### *Parameters* - -key1, key2, keyN: keys identifying the different sets on which we will apply the intersection. - -###### *Return value* - -Array, containing the result of the intersection between those keys. If the intersection between the different sets is empty, the return value will be an empty array. - -###### *Examples* -~~~php -$redis->sAdd('key1', 'val1'); -$redis->sAdd('key1', 'val2'); -$redis->sAdd('key1', 'val3'); -$redis->sAdd('key1', 'val4'); - -$redis->sAdd('key2', 'val3'); -$redis->sAdd('key2', 'val4'); - -$redis->sAdd('key3', 'val3'); -$redis->sAdd('key3', 'val4'); - -var_dump($redis->sInter('key1', 'key2', 'key3')); -~~~ - -Output: - -~~~ -array(2) { - [0]=> - string(4) "val4" - [1]=> - string(4) "val3" -} -~~~ - -#### sInterStore ------ -_**Description**_: Performs a sInter command and stores the result in a new set. -###### *Parameters* -*Key*: dstkey, the key to store the diff into. - -*Keys*: key1, key2... keyN. key1..keyN are intersected as in sInter. - -###### *Return value* -*INTEGER*: The cardinality of the resulting set, or `FALSE` in case of a missing key. - -###### *Example* -~~~php -$redis->sAdd('key1', 'val1'); -$redis->sAdd('key1', 'val2'); -$redis->sAdd('key1', 'val3'); -$redis->sAdd('key1', 'val4'); - -$redis->sAdd('key2', 'val3'); -$redis->sAdd('key2', 'val4'); - -$redis->sAdd('key3', 'val3'); -$redis->sAdd('key3', 'val4'); - -var_dump($redis->sInterStore('output', 'key1', 'key2', 'key3')); -var_dump($redis->sMembers('output')); -~~~ - -Output: - -~~~ -int(2) - -array(2) { - [0]=> - string(4) "val4" - [1]=> - string(4) "val3" -} -~~~ - -#### sIsMember ------ -_**Description**_: Checks if `value` is a member of the set stored at the key `key`. -###### *Parameters* -*key* -*value* - -###### *Return value* -*BOOL* `TRUE` if `value` is a member of the set at key `key`, `FALSE` otherwise. -###### *Example* -~~~php -$redis->sAdd('key1' , 'member1'); -$redis->sAdd('key1' , 'member2'); -$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/ - -$redis->sIsMember('key1', 'member1'); /* TRUE */ -$redis->sIsMember('key1', 'memberX'); /* FALSE */ -~~~ - -#### sMembers ------ -_**Description**_: Returns the contents of a set. - -###### *Parameters* -*Key*: key - -###### *Return value* -An array of elements, the contents of the set. - -###### *Example* -~~~php -$redis->del('s'); -$redis->sAdd('s', 'a'); -$redis->sAdd('s', 'b'); -$redis->sAdd('s', 'a'); -$redis->sAdd('s', 'c'); -var_dump($redis->sMembers('s')); -~~~ - -Output: -~~~ -array(3) { - [0]=> - string(1) "c" - [1]=> - string(1) "a" - [2]=> - string(1) "b" -} -~~~ -The order is random and corresponds to redis' own internal representation of the set structure. - -#### sMove ------ -_**Description**_: Moves the specified member from the set at srcKey to the set at dstKey. -###### *Parameters* -*srcKey* -*dstKey* -*member* -###### *Return value* -*BOOL* If the operation is successful, return `TRUE`. If the srcKey and/or dstKey didn't exist, and/or the member didn't exist in srcKey, `FALSE` is returned. -###### *Example* -~~~php -$redis->sAdd('key1' , 'member11'); -$redis->sAdd('key1' , 'member12'); -$redis->sAdd('key1' , 'member13'); /* 'key1' => {'member11', 'member12', 'member13'}*/ -$redis->sAdd('key2' , 'member21'); -$redis->sAdd('key2' , 'member22'); /* 'key2' => {'member21', 'member22'}*/ -$redis->sMove('key1', 'key2', 'member13'); /* 'key1' => {'member11', 'member12'} */ - /* 'key2' => {'member21', 'member22', 'member13'} */ - -~~~ - -#### sPop ------ -_**Description**_: Removes and returns a random element from the set value at Key. -###### *Parameters* -*key* -*count*: Integer, optional -###### *Return value (without count argument)* -*String* "popped" value -*Bool* `FALSE` if set identified by key is empty or doesn't exist. -###### *Return value (with count argument)* -*Array*: Member(s) returned or an empty array if the set doesn't exist -*Bool*: `FALSE` on error if the key is not a set -###### *Example* -~~~php -$redis->sAdd('key1' , 'member1'); -$redis->sAdd('key1' , 'member2'); -$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/ -$redis->sPop('key1'); /* 'member1', 'key1' => {'member3', 'member2'} */ -$redis->sPop('key1'); /* 'member3', 'key1' => {'member2'} */ - -/* With count */ -$redis->sAdd('key2', 'member1', 'member2', 'member3'); -$redis->sPop('key2', 3); /* Will return all members but in no particular order */ -~~~ - -#### sRandMember ------ -_**Description**_: Returns a random element from the set value at Key, without removing it. -###### *Parameters* -*key* -*count* (Integer, optional) -###### *Return value* -If no count is provided, a random *String* value from the set will be returned. If a count -is provided, an array of values from the set will be returned. Read about the different -ways to use the count here: [SRANDMEMBER](http://redis.io/commands/srandmember) -*Bool* `FALSE` if set identified by key is empty or doesn't exist. -###### *Example* -~~~php -$redis->sAdd('key1' , 'member1'); -$redis->sAdd('key1' , 'member2'); -$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member3', 'member1', 'member2'}*/ - -// No count -$redis->sRandMember('key1'); /* 'member1', 'key1' => {'member3', 'member1', 'member2'} */ -$redis->sRandMember('key1'); /* 'member3', 'key1' => {'member3', 'member1', 'member2'} */ - -// With a count -$redis->sRandMember('key1', 3); // Will return an array with all members from the set -$redis->sRandMember('key1', 2); // Will an array with 2 members of the set -$redis->sRandMember('key1', -100); // Will return an array of 100 elements, picked from our set (with dups) -$redis->sRandMember('empty-set', 100); // Will return an empty array -$redis->sRandMember('not-a-set', 100); // Will return FALSE -~~~ - -#### sRem ------ -_**Description**_: Removes the specified member from the set value stored at key. -###### *Parameters* -*key* -*member* -###### *Return value* -*LONG* The number of elements removed from the set. -###### *Example* -~~~php -$redis->sAdd('key1' , 'member1'); -$redis->sAdd('key1' , 'member2'); -$redis->sAdd('key1' , 'member3'); /* 'key1' => {'member1', 'member2', 'member3'}*/ -$redis->sRem('key1', 'member2', 'member3'); /*return 2. 'key1' => {'member1'} */ -~~~ - -#### sUnion ------ -_**Description**_: Performs the union between N sets and returns it. - -###### *Parameters* -*Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis. - -###### *Return value* -*Array of strings*: The union of all these sets. - -**Note:** `sUnion` can also take a single array with keys (see example below). - -###### *Example* -~~~php -$redis->del('s0', 's1', 's2'); - -$redis->sAdd('s0', '1'); -$redis->sAdd('s0', '2'); -$redis->sAdd('s1', '3'); -$redis->sAdd('s1', '1'); -$redis->sAdd('s2', '3'); -$redis->sAdd('s2', '4'); - -/* Get the union with variadic arguments */ -var_dump($redis->sUnion('s0', 's1', 's2')); - -/* Pass a single array */ -var_dump($redis->sUnion(['s0', 's1', 's2'])); - -~~~ -Return value: all elements that are either in s0 or in s1 or in s2. -~~~ -array(4) { - [0]=> - string(1) "3" - [1]=> - string(1) "4" - [2]=> - string(1) "1" - [3]=> - string(1) "2" -} -~~~ - -#### sUnionStore ------ -_**Description**_: Performs the same action as sUnion, but stores the result in the first key - -###### *Parameters* -*Key*: dstkey, the key to store the diff into. - -*Keys*: key1, key2, ... , keyN: Any number of keys corresponding to sets in redis. - -###### *Return value* -*INTEGER*: The cardinality of the resulting set, or `FALSE` in case of a missing key. - -###### *Example* -~~~php -$redis->del('s0', 's1', 's2'); - -$redis->sAdd('s0', '1'); -$redis->sAdd('s0', '2'); -$redis->sAdd('s1', '3'); -$redis->sAdd('s1', '1'); -$redis->sAdd('s2', '3'); -$redis->sAdd('s2', '4'); - -var_dump($redis->sUnionStore('dst', 's0', 's1', 's2')); -var_dump($redis->sMembers('dst')); -~~~ -Return value: the number of elements that are either in s0 or in s1 or in s2. -~~~ -int(4) -array(4) { - [0]=> - string(1) "3" - [1]=> - string(1) "4" - [2]=> - string(1) "1" - [3]=> - string(1) "2" -} -~~~ - -#### sScan ------ -_**Description**_: Scan a set for members - -###### *Parameters* -*Key*: The set to search -*iterator*: LONG (reference) to the iterator as we go -*pattern*: String, optional pattern to match against -*count*: How many members to return at a time (Redis might return a different amount) - -###### *Return value* -*Array, boolean*: PHPRedis will return an array of keys or FALSE when we're done iterating - -###### *Example* -~~~php -$it = NULL; -$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); /* don't return empty results until we're done */ -while($arr_mems = $redis->sScan('set', $it, "*pattern*")) { - foreach($arr_mems as $str_mem) { - echo "Member: $str_mem\n"; - } -} - -$it = NULL; -$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY); /* return after each iteration, even if empty */ -while(($arr_mems = $redis->sScan('set', $it, "*pattern*"))!==FALSE) { - if(count($arr_mems) > 0) { - foreach($arr_mems as $str_mem) { - echo "Member found: $str_mem\n"; - } - } else { - echo "No members in this iteration, iterator value: $it\n"; - } -} -~~~ - -### Sorted sets - -* [bzPop](#bzpop) - Block until Redis can pop the highest or lowest scoring member from one or more ZSETs. -* [zAdd](#zadd) - Add one or more members to a sorted set or update its score if it already exists -* [zCard](#zcard) - Get the number of members in a sorted set -* [zCount](#zcount) - Count the members in a sorted set with scores within the given values -* [zDiff](#zdiff) - Computes the difference between the first and all successive input sorted sets and return the resulting sorted set -* [zdiffstore](#zdiffstore) - Computes the difference between the first and all successive input sorted sets and stores the result in a new key -* [zIncrBy](#zincrby) - Increment the score of a member in a sorted set -* [zInter](#zinter) - Intersect multiple sorted sets and return the resulting sorted set -* [zinterstore](#zinterstore) - Intersect multiple sorted sets and store the resulting sorted set in a new key -* [zMscore](#zmscore) - Get the scores associated with the given members in a sorted set -* [zPop](#zpop) - Redis can pop the highest or lowest scoring member from one a ZSET. -* [zRange](#zrange) - Return a range of members in a sorted set, by index -* [zRangeByScore, zRevRangeByScore](#zrangebyscore-zrevrangebyscore) - Return a range of members in a sorted set, by score -* [zRangeByLex](#zrangebylex) - Return a lexicographical range from members that share the same score -* [zRank, zRevRank](#zrank-zrevrank) - Determine the index of a member in a sorted set -* [zRem](#zrem) - Remove one or more members from a sorted set -* [zRemRangeByRank](#zremrangebyrank) - Remove all members in a sorted set within the given indexes -* [zRemRangeByScore](#zremrangebyscore) - Remove all members in a sorted set within the given scores -* [zRevRange](#zrevrange) - Return a range of members in a sorted set, by index, with scores ordered from high to low -* [zScore](#zscore) - Get the score associated with the given member in a sorted set -* [zUnion](#zunion) - Add multiple sorted sets and return the resulting sorted set -* [zunionstore](#zunionstore) - Add multiple sorted sets and store the resulting sorted set in a new key -* [zScan](#zscan) - Scan a sorted set for members - -#### bzPop ------ -_**Description**_: Block until Redis can pop the highest or lowest scoring members from one or more ZSETs. There are two commands (`BZPOPMIN` and `BZPOPMAX` for popping the lowest and highest scoring elements respectively.) - -###### *Prototype* -~~~php -$redis->bzPopMin(array $keys, int $timeout): array -$redis->bzPopMax(array $keys, int $timeout): array - -$redis->bzPopMin(string $key1, string $key2, ... int $timeout): array -$redis->bzPopMax(string $key1, string $key2, ... int $timeout): array -~~~ - -###### *Return value* -*ARRAY:* Either an array with the key member and score of the highest or lowest element or an empty array if the timeout was reached without an element to pop. - -###### *Example* -~~~php -/* Wait up to 5 seconds to pop the *lowest* scoring member from sets `zs1` and `zs2`. */ -$redis->bzPopMin(['zs1', 'zs2'], 5); -$redis->bzPopMin('zs1', 'zs2', 5); - -/* Wait up to 5 seconds to pop the *highest* scoring member from sets `zs1` and `zs2` */ -$redis->bzPopMax(['zs1', 'zs2'], 5); -$redis->bzPopMax('zs1', 'zs2', 5); -~~~ - -**Note:** Calling these functions with an array of keys or with a variable number of arguments is functionally identical. - -#### zAdd ------ -_**Description**_: Add one or more members to a sorted set or update its score if it already exists - - -###### *Prototype* -~~~php -$redis->zAdd($key, [ $options ,] $score, $value [, $score1, $value1, ...]); -~~~ - -###### *Parameters* -*key*: string -*options*: array (optional) -*score*: double -*value*: string -*score1*: double -*value1*: string - -###### *Return value* -*Long* 1 if the element is added. 0 otherwise. - -###### *Example* -~~~php -$redis->zAdd('key', 1, 'val1'); -$redis->zAdd('key', 0, 'val0'); -$redis->zAdd('key', 5, 'val5'); -$redis->zRange('key', 0, -1); // [val0, val1, val5] - -// From Redis 3.0.2 it's possible to add options like XX, NX, CH, INCR -$redis->zAdd('key', ['CH'], 5, 'val5', 10, 'val10', 15, 'val15'); -~~~ - -#### zCard ------ -_**Description**_: Returns the cardinality of an ordered set. - -###### *Parameters* -*key* - -###### *Return value* -*Long*, the set's cardinality - -###### *Example* -~~~php -$redis->zAdd('key', 0, 'val0'); -$redis->zAdd('key', 2, 'val2'); -$redis->zAdd('key', 10, 'val10'); -$redis->zCard('key'); /* 3 */ -~~~ - -#### zCount ------ -_**Description**_: Returns the *number* of elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before `start` or `end` excludes it from the range. +inf and -inf are also valid limits. - -###### *Parameters* -*key* -*start*: string -*end*: string - -###### *Return value* -*LONG* the size of a corresponding zRangeByScore. - -###### *Example* -~~~php -$redis->zAdd('key', 0, 'val0'); -$redis->zAdd('key', 2, 'val2'); -$redis->zAdd('key', 10, 'val10'); -$redis->zCount('key', 0, 3); /* 2, corresponding to ['val0', 'val2'] */ -~~~ - -#### zDiff ------ -_**Description**_: Computes the difference between the first and all successive input sorted sets in the first argument. The result of the difference will be returned. - -The second argument is a set of options. It can define `WITHSCORES` so that the scores are returned as well. - -###### *Parameters* -*arrayZSetKeys* -*arrayOptions* One option is available: `withscores => TRUE`. - -###### *Return value* -*ARRAY* The result of the difference of sets. - -###### *Example* -~~~php -$redis->del('k1'); -$redis->del('k2'); -$redis->del('k3'); - -$redis->zAdd('k1', 0, 'val0'); -$redis->zAdd('k1', 1, 'val1'); -$redis->zAdd('k1', 3, 'val3'); - -$redis->zAdd('k2', 5, 'val1'); - -$redis->zAdd('k3', 5, 'val0'); -$redis->zAdd('k3', 3, 'val4'); - -$redis->zDiff(['k1', 'k2']); /* ['val0', 'val3'] */ -$redis->zDiff(['k2', 'k1']); /* [] */ -$redis->zDiff(['k1', 'k2'], ['withscores' => true]); /* ['val0' => 0.0, 'val3' => 3.0] */ - -$redis->zDiff(['k1', 'k2', 'k3']); /* ['val3'] */ -$redis->zDiff(['k3', 'k2', 'k1']); /* ['val4'] */ -~~~ - -#### zdiffstore ------ -_**Description**_: Computes the difference between the first and all successive input sorted sets in the second argument. The result of the difference will be stored in the sorted set defined by the first argument. - -###### *Parameters* -*keyOutput* -*arrayZSetKeys* - -###### *Return value* -*LONG* The number of values in the new sorted set. - -###### *Example* -~~~php -$redis->del('k1'); -$redis->del('k2'); -$redis->del('k3'); - -$redis->zAdd('k1', 0, 'val0'); -$redis->zAdd('k1', 1, 'val1'); -$redis->zAdd('k1', 3, 'val3'); - -$redis->zAdd('k2', 5, 'val1'); - -$redis->zAdd('k3', 5, 'val0'); -$redis->zAdd('k3', 3, 'val4'); - -$redis->zdiffstore('ko1', ['k1', 'k2']); /* 2, 'ko1' => ['val0', 'val3'] */ -$redis->zdiffstore('ko2', ['k2', 'k1']); /* 0, 'ko2' => [] */ - -$redis->zdiffstore('ko3', ['k1', 'k2', 'k3']); /* 1, 'ko3' => ['val3'] */ -$redis->zdiffstore('ko4', ['k3', 'k2', 'k1']); /* 1, 'k04' => ['val4'] */ -~~~ - -#### zIncrBy ------ -_**Description**_: Increments the score of a member from a sorted set by a given amount. - -###### *Parameters* -*key* -*value*: (double) value that will be added to the member's score -*member* - -###### *Return value* -*DOUBLE* the new value - -###### *Examples* -~~~php -$redis->del('key'); -$redis->zIncrBy('key', 2.5, 'member1'); /* key or member1 didn't exist, so member1's score is to 0 before the increment */ - /* and now has the value 2.5 */ -$redis->zIncrBy('key', 1, 'member1'); /* 3.5 */ -~~~ - -#### zInter ------ -_**Description**_: Creates an intersection of sorted sets given in first argument. The result of the intersection will be returned. - -The second optional argument defines `weights` to apply to the sorted sets in input. In this case, the `weights` will be multiplied by the score of each element in the sorted set before applying the aggregation. -The third argument is a set of options. It can define the `AGGREGATE` option which specify how the results of the intersection are aggregated. It can also define `WITHSCORES` so that the scores are returned as well. - -###### *Parameters* -*arrayZSetKeys* -*arrayWeights* -*arrayOptions* Two options are available: `withscores => TRUE`, and `aggregate => $behaviour`. Either "SUM", "MIN", or "MAX" defines the behaviour to use on duplicate entries during the zinter. - -###### *Return value* -*ARRAY* The result of the intersection of sets. - -###### *Example* -~~~php -$redis->del('k1'); -$redis->del('k2'); -$redis->del('k3'); - -$redis->zAdd('k1', 0, 'val0'); -$redis->zAdd('k1', 1, 'val1'); -$redis->zAdd('k1', 3, 'val3'); - -$redis->zAdd('k2', 5, 'val1'); -$redis->zAdd('k2', 3, 'val3'); - -$redis->zinter(['k1', 'k2']); /* ['val1', 'val3'] */ -$redis->zinter(['k1', 'k2'], [1, 1]); /* ['val1', 'val3'] */ - -/* Weighted zinter */ -$redis->zinter(['k1', 'k2'], [1, 5], 'min'); /* ['val1', 'val3'] */ -$redis->zinter(['k1', 'k2'], [1, 5], 'max'); /* ['val3', 'val1'] */ -~~~ - -#### zinterstore ------ -_**Description**_: Creates an intersection of sorted sets given in second argument. The result of the intersection will be stored in the sorted set defined by the first argument. - -The third optional argument defines `weights` to apply to the sorted sets in input. In this case, the `weights` will be multiplied by the score of each element in the sorted set before applying the aggregation. -The forth argument defines the `AGGREGATE` option which specify how the results of the intersection are aggregated. - -###### *Parameters* -*keyOutput* -*arrayZSetKeys* -*arrayWeights* -*aggregateFunction* Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zinterstore. - -###### *Return value* -*LONG* The number of values in the new sorted set. - -###### *Example* -~~~php -$redis->del('k1'); -$redis->del('k2'); -$redis->del('k3'); - -$redis->del('ko1'); -$redis->del('ko2'); -$redis->del('ko3'); -$redis->del('ko4'); - -$redis->zAdd('k1', 0, 'val0'); -$redis->zAdd('k1', 1, 'val1'); -$redis->zAdd('k1', 3, 'val3'); - -$redis->zAdd('k2', 5, 'val1'); -$redis->zAdd('k2', 3, 'val3'); - -$redis->zinterstore('ko1', ['k1', 'k2']); /* 2, 'ko1' => ['val1', 'val3'] */ -$redis->zinterstore('ko2', ['k1', 'k2'], [1, 1]); /* 2, 'ko2' => ['val1', 'val3'] */ - -/* Weighted zinterstore */ -$redis->zinterstore('ko3', ['k1', 'k2'], [1, 5], 'min'); /* 2, 'ko3' => ['val1', 'val3'] */ -$redis->zinterstore('ko4', ['k1', 'k2'], [1, 5], 'max'); /* 2, 'ko4' => ['val3', 'val1'] */ -~~~ - -#### zMscore ------ -_**Description**_: Returns the scores of the given members in the specified sorted set. - -###### *Parameters* -*key* -*members*: member1, member2, ... , memberN: Any number of members in the specified sorted set. - -###### *Return value* -*ARRAY* or *FALSE* when the key is not found. Array entries corresponding to members that do not exist will be `false`. - -###### *Example* -~~~php -$redis->zAdd('key', 2.5, 'val2'); -$redis->zAdd('key', 4.5, 'val4'); - -$redis->zMscore('key', 'val2', 'val3', 'val4'); /* [2.5, false, 4.5] */ -~~~ - -#### zPop ------ -_**Description**_: Can pop the highest or lowest scoring members from one ZSETs. There are two commands (`ZPOPMIN` and `ZPOPMAX` for popping the lowest and highest scoring elements respectively.) - -###### *Prototype* -~~~php -$redis->zPopMin(string $key, int $count): array -$redis->zPopMax(string $key, int $count): array - -$redis->zPopMin(string $key, int $count): array -$redis->zPopMax(string $key, int $count): array -~~~ - -###### *Return value* -*ARRAY:* Either an array with the key member and score of the highest or lowest element or an empty array if there is no element available. - -###### *Example* -~~~php -/* Pop the *lowest* scoring member from set `zs1`. */ -$redis->zPopMin('zs1', 5); - -/* Pop the *highest* scoring member from set `zs1`. */ -$redis->zPopMax('zs1', 5); -~~~ - -#### zRange ------ -_**Description**_: Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end]. - -Start and stop are interpreted as zero-based indices: -`0` the first element, `1` the second ... -`-1` the last element, `-2` the penultimate ... - -###### *Parameters* -*key* -*start*: long -*end*: long -*withscores*: bool = false - -###### *Return value* -*Array* containing the values in specified range. - -###### *Example* -~~~php -$redis->zAdd('key1', 0, 'val0'); -$redis->zAdd('key1', 2, 'val2'); -$redis->zAdd('key1', 10, 'val10'); -$redis->zRange('key1', 0, -1); /* ['val0', 'val2', 'val10'] */ - -// with scores -$redis->zRange('key1', 0, -1, true); /* ['val0' => 0, 'val2' => 2, 'val10' => 10] */ -~~~ - -#### zRangeByScore, zRevRangeByScore ------ -_**Description**_: Returns the elements of the sorted set stored at the specified key which have scores in the range [start,end]. Adding a parenthesis before `start` or `end` excludes it from the range. +inf and -inf are also valid limits. zRevRangeByScore returns the same items in reverse order, when the `start` and `end` parameters are swapped. - -###### *Parameters* -*key* -*start*: string -*end*: string -*options*: array - -Two options are available: `withscores => TRUE`, and `limit => [$offset, $count]` - -###### *Return value* -*Array* containing the values in specified range. - -###### *Example* -~~~php -$redis->zAdd('key', 0, 'val0'); -$redis->zAdd('key', 2, 'val2'); -$redis->zAdd('key', 10, 'val10'); -$redis->zRangeByScore('key', 0, 3); /* ['val0', 'val2'] */ -$redis->zRangeByScore('key', 0, 3, ['withscores' => TRUE]); /* ['val0' => 0, 'val2' => 2] */ -$redis->zRangeByScore('key', 0, 3, ['limit' => [1, 1]]); /* ['val2'] */ -$redis->zRangeByScore('key', 0, 3, ['withscores' => TRUE, 'limit' => [1, 1]]); /* ['val2' => 2] */ -$redis->zRangeByScore('key', '-inf', '+inf', ['withscores' => TRUE]); /* ['val0' => 0, 'val2' => 2, 'val10' => 10] */ -~~~ - -#### zRangeByLex ------ -_**Description**_: Returns a lexicographical range of members in a sorted set, assuming the members have the same score. The min and max values are required to start with '(' (exclusive), '[' (inclusive), or be exactly the values '-' (negative inf) or '+' (positive inf). The command must be called with either three *or* five arguments or will return FALSE. - -###### *Parameters* -*key*: The ZSET you wish to run against -*min*: The minimum alphanumeric value you wish to get -*max*: The maximum alphanumeric value you wish to get -*offset*: Optional argument if you wish to start somewhere other than the first element. -*limit*: Optional argument if you wish to limit the number of elements returned. - -###### *Return value* -*Array* containing the values in the specified range. - -###### *Example* -~~~php -foreach(['a','b','c','d','e','f','g'] as $c) - $redis->zAdd('key',0,$c); - -$redis->zRangeByLex('key','-','[c') /* ['a','b','c']; */ -$redis->zRangeByLex('key','-','(c') /* ['a','b'] */ -$redis->zRangeByLex('key','-','[c',1,2) /* ['b','c'] */ -~~~ - -#### zRank, zRevRank ------ -_**Description**_: Returns the rank of a given member in the specified sorted set, starting at 0 for the item with the smallest score. zRevRank starts at 0 for the item with the *largest* score. - -###### *Parameters* -*key* -*member* - -###### *Return value* -*Long*, the item's rank. - -###### *Example* -~~~php -$redis->del('z'); -$redis->zAdd('key', 1, 'one'); -$redis->zAdd('key', 2, 'two'); -$redis->zRank('key', 'one'); /* 0 */ -$redis->zRank('key', 'two'); /* 1 */ -$redis->zRevRank('key', 'one'); /* 1 */ -$redis->zRevRank('key', 'two'); /* 0 */ -~~~ - -#### zRem ------ -_**Description**_: Delete one or more members from a sorted set. - -###### *Prototype* -~~~php -$redis->zRem($key, $member [, $member ...]); -~~~ - -###### *Return value* -*LONG:* The number of members deleted. - -###### *Example* -~~~php -$redis->zAdd('key', 0, 'val0', 1, 'val1', 2, 'val2'); -$redis->zRem('key', 'val0', 'val1', 'val2'); // Returns: 3 -~~~ - -#### zRemRangeByRank ------ -_**Description**_: Deletes the elements of the sorted set stored at the specified key which have rank in the range [start,end]. - -###### *Parameters* -*key* -*start*: LONG -*end*: LONG - -###### *Return value* -*LONG* The number of values deleted from the sorted set - -###### *Example* -~~~php -$redis->zAdd('key', 1, 'one'); -$redis->zAdd('key', 2, 'two'); -$redis->zAdd('key', 3, 'three'); -$redis->zRemRangeByRank('key', 0, 1); /* 2 */ -$redis->zRange('key', 0, -1, ['withscores' => TRUE]); /* ['three' => 3] */ -~~~ - -#### zRemRangeByScore ------ -_**Description**_: Deletes the elements of the sorted set stored at the specified key which have scores in the range [start,end]. - -###### *Parameters* -*key* -*start*: double or "+inf" or "-inf" string -*end*: double or "+inf" or "-inf" string - -###### *Return value* -*LONG* The number of values deleted from the sorted set - -###### *Example* -~~~php -$redis->zAdd('key', 0, 'val0'); -$redis->zAdd('key', 2, 'val2'); -$redis->zAdd('key', 10, 'val10'); -$redis->zRemRangeByScore('key', 0, 3); /* 2 */ -~~~ - -#### zRevRange ------ -_**Description**_: Returns the elements of the sorted set stored at the specified key in the range [start, end] in reverse order. start and stop are interpreted as zero-based indices: -`0` the first element, `1` the second ... -`-1` the last element, `-2` the penultimate ... - -###### *Parameters* -*key* -*start*: long -*end*: long -*withscores*: bool = false - -###### *Return value* -*Array* containing the values in specified range. - -###### *Example* -~~~php -$redis->zAdd('key', 0, 'val0'); -$redis->zAdd('key', 2, 'val2'); -$redis->zAdd('key', 10, 'val10'); -$redis->zRevRange('key', 0, -1); /* ['val10', 'val2', 'val0'] */ - -// with scores -$redis->zRevRange('key', 0, -1, true); /* ['val10' => 10, 'val2' => 2, 'val0' => 0] */ -~~~ - -#### zScore ------ -_**Description**_: Returns the score of a given member in the specified sorted set. - -###### *Parameters* -*key* -*member* - -###### *Return value* -*Double* or *FALSE* when the value is not found - -###### *Example* -~~~php -$redis->zAdd('key', 2.5, 'val2'); -$redis->zScore('key', 'val2'); /* 2.5 */ -~~~ - -#### zUnion ------ -_**Description**_: Creates an union of sorted sets given in first argument. The result of the union will be returned. - -The second optional argument defines `weights` to apply to the sorted sets in input. In this case, the `weights` will be multiplied by the score of each element in the sorted set before applying the aggregation. -The third argument is a set of options. It can define the `AGGREGATE` option which specify how the results of the intersection are aggregated. It can also define `WITHSCORES` so that the scores are returned as well. - -###### *Parameters* -*arrayZSetKeys* -*arrayWeights* -*arrayOptions* Two options are available: `withscores => TRUE`, and `aggregate => $behaviour`. Either "SUM", "MIN", or "MAX" defines the behaviour to use on duplicate entries during the zunion. - -###### *Return value* -*ARRAY* The result of the union of sets. - -###### *Example* -~~~php -$redis->del('k1'); -$redis->del('k2'); -$redis->del('k3'); - -$redis->zAdd('k1', 0, 'val0'); -$redis->zAdd('k1', 1, 'val1'); - -$redis->zAdd('k2', 2, 'val2'); -$redis->zAdd('k2', 3, 'val3'); - -$redis->zunion(['k1', 'k2']); /* ['val0', 'val1', 'val2', 'val3'] */ - -/* Weighted zunion */ -$redis->zunion(['k1', 'k2'], [1, 1]); /* ['val0', 'val1', 'val2', 'val3'] */ -$redis->zunion(['k1', 'k2'], [5, 1]); /* ['val0', 'val2', 'val3', 'val1'] */ -~~~ - -#### zunionstore ------ -_**Description**_: Creates an union of sorted sets given in second argument. The result of the union will be stored in the sorted set defined by the first argument. - -The third optional argument defines `weights` to apply to the sorted sets in input. In this case, the `weights` will be multiplied by the score of each element in the sorted set before applying the aggregation. -The forth argument defines the `AGGREGATE` option which specify how the results of the union are aggregated. - -###### *Parameters* -*keyOutput* -*arrayZSetKeys* -*arrayWeights* -*aggregateFunction* Either "SUM", "MIN", or "MAX": defines the behaviour to use on duplicate entries during the zunionstore. - -###### *Return value* -*LONG* The number of values in the new sorted set. - -###### *Example* -~~~php -$redis->del('k1'); -$redis->del('k2'); -$redis->del('k3'); -$redis->del('ko1'); -$redis->del('ko2'); -$redis->del('ko3'); - -$redis->zAdd('k1', 0, 'val0'); -$redis->zAdd('k1', 1, 'val1'); - -$redis->zAdd('k2', 2, 'val2'); -$redis->zAdd('k2', 3, 'val3'); - -$redis->zunionstore('ko1', ['k1', 'k2']); /* 4, 'ko1' => ['val0', 'val1', 'val2', 'val3'] */ - -/* Weighted zunionstore */ -$redis->zunionstore('ko2', ['k1', 'k2'], [1, 1]); /* 4, 'ko2' => ['val0', 'val1', 'val2', 'val3'] */ -$redis->zunionstore('ko3', ['k1', 'k2'], [5, 1]); /* 4, 'ko3' => ['val0', 'val2', 'val3', 'val1'] */ -~~~ - -#### zScan ------ -_**Description**_: Scan a sorted set for members, with optional pattern and count - -###### *Parameters* -*key*: String, the set to scan -*iterator*: Long (reference), initialized to NULL -*pattern*: String (optional), the pattern to match -*count*: How many keys to return per iteration (Redis might return a different number) - -###### *Return value* -*Array, boolean* PHPRedis will return matching keys from Redis, or FALSE when iteration is complete - -###### *Example* -~~~php -$it = NULL; -$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); -while($arr_matches = $redis->zScan('zset', $it, '*pattern*')) { - foreach($arr_matches as $str_mem => $f_score) { - echo "Key: $str_mem, Score: $f_score\n"; - } -} -~~~ - -### HyperLogLogs - -#### pfAdd ------ - -_**Description**_: Adds the specified elements to the specified HyperLogLog. - -###### *Prototype* -~~~php -$redis->pfAdd($key, Array $elements); -~~~ - -###### *Parameters* -_Key_ -_Array of values_ - -###### *Return value* -*Integer*: 1 if at least 1 HyperLogLog internal register was altered. 0 otherwise. - -###### *Example* -~~~php -$redis->pfAdd('hll', ['a', 'b', 'c']); // (int) 1 -$redis->pfAdd('hll', ['a', 'b']); // (int) 0 -~~~ - -#### pfCount ------ - -_**Description**_: Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s). - -###### *Prototype* -~~~php -$redis->pfCount($key); -$redis->pfCount(Array $keys); -~~~ - -###### *Parameters* -_Key_ or _Array of keys_ - -###### *Return value* -*Integer*: The approximated number of unique elements observed via [pfAdd](#pfAdd). - -###### *Example* -~~~php -$redis->pfAdd('hll1', ['a', 'b', 'c']); // (int) 1 -$redis->pfCount('hll1'); // (int) 3 - -$redis->pfAdd('hll2', ['d', 'e', 'a']); // (int) 1 -$redis->pfCount('hll2'); // (int) 3 - -$redis->pfCount(['hll1', 'hll2']); // (int) 5 -~~~ - -#### pfMerge ------ - -_**Description**_: Merge N different HyperLogLogs into a single one. - -###### *Prototype* -~~~php -$redis->pfMerge($destkey, Array $sourceKeys); -~~~ - -###### *Parameters* -_Destination Key_ -_Array of Source Keys_ - -###### *Return value* -*BOOL*: `TRUE` on success, `FALSE` on error. - -###### *Example* -~~~php -$redis->pfAdd('hll1', ['a', 'b', 'c']); // (int) 1 -$redis->pfAdd('hll2', ['d', 'e', 'a']); // (int) 1 - -$redis->pfMerge('hll3', ['hll1', 'hll2']); // true - -$redis->pfCount('hll3'); // (int) 5 -~~~ - -### Geocoding - -#### geoAdd ------ - -###### *Prototype* -~~~php -$redis->geoAdd($key, $longitude, $latitude, $member [, $longitude, $latitude, $member, ...]); -~~~ - -_**Description**_: Add one or more geospatial items to the specified key. This function must be called with at least one _longitude, latitude, member_ triplet. - -###### *Return value* -*Integer*: The number of elements added to the geospatial key. - -###### *Example* -~~~php -$redis->del("myplaces"); - -/* Since the key will be new, $result will be 2 */ -$result = $redis->geoAdd( - "myplaces", - -122.431, 37.773, "San Francisco", - -157.858, 21.315, "Honolulu" -); -~~~ - -#### geoHash ------ - -###### *Prototype* -~~~php -$redis->geoHash($key, $member [, $member, $member, ...]); -~~~ - -_**Description**_: Retrieve Geohash strings for one or more elements of a geospatial index. - -###### *Return value* -*Array*: One or more Redis Geohash encoded strings. - -###### *Example* -~~~php -$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui"); -$hashes = $redis->geoHash("hawaii", "Honolulu", "Maui"); -var_dump($hashes); -~~~ - -###### *Output* -~~~ -array(2) { - [0]=> - string(11) "87z9pyek3y0" - [1]=> - string(11) "8e8y6d5jps0" -} -~~~ - -#### geoPos ------ - -###### *Prototype* -~~~php -$redis->geoPos($key, $member [, $member, $member, ...]); -~~~ - -_**Description**_: Return longitude, latitude positions for each requested member. - -###### *Return value* -*Array*: One or more longitude/latitude positions - -###### *Example* -~~~php -$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui"); -$positions = $redis->geoPos("hawaii", "Honolulu", "Maui"); -var_dump($positions); -~~~ - -###### *Output* -~~~ -array(2) { - [0]=> - array(2) { - [0]=> - string(22) "-157.85800248384475708" - [1]=> - string(19) "21.3060004581273077" - } - [1]=> - array(2) { - [0]=> - string(22) "-156.33099943399429321" - [1]=> - string(20) "20.79799924753607598" - } -} -~~~ - -#### GeoDist ------ - -###### *Prototype* -~~~php -$redis->geoDist($key, $member1, $member2 [, $unit]); -~~~ - - -_**Description**_: Return the distance between two members in a geospatial set. If units are passed it must be one of the following values: - -* 'm' => Meters -* 'km' => Kilometers -* 'mi' => Miles -* 'ft' => Feet - -###### *Return value* -*Double*: The distance between the two passed members in the units requested (meters by default). - -###### *Example* -~~~php -$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui"); - -$meters = $redis->geoDist("hawaii", "Honolulu", "Maui"); -$kilometers = $redis->geoDist("hawaii", "Honolulu", "Maui", 'km'); -$miles = $redis->geoDist("hawaii", "Honolulu", "Maui", 'mi'); -$feet = $redis->geoDist("hawaii", "Honolulu", "Maui", 'ft'); - -echo "Distance between Honolulu and Maui:\n"; -echo " meters : $meters\n"; -echo " kilometers: $kilometers\n"; -echo " miles : $miles\n"; -echo " feet : $feet\n"; - -/* Bad unit */ -$inches = $redis->geoDist("hawaii", "Honolulu", "Maui", 'in'); -echo "Invalid unit returned:\n"; -var_dump($inches); -~~~ - -###### *Output* -~~~ -Distance between Honolulu and Maui: - meters : 168275.204 - kilometers: 168.2752 - miles : 104.5616 - feet : 552084.0028 -Invalid unit returned: -bool(false) -~~~ - -#### geoRadius ------ - -###### *Prototype* -~~~php -$redis->geoRadius($key, $longitude, $latitude, $radius, $unit [, Array $options]); -~~~ - -_**Description**_: Return members of a set with geospatial information that are within the radius specified by the caller. - -###### *Options Array* -The georadius command can be called with various options that control how Redis returns results. The following table describes the options phpredis supports. All options are case insensitive. - -| Key | Value | Description -| :--- | :--- | :---- | -| COUNT | integer > 0 | Limit how many results are returned -| | WITHCOORD | Return longitude and latitude of matching members -| | WITHDIST | Return the distance from the center -| | WITHHASH | Return the raw geohash-encoded score -| | ASC | Sort results in ascending order -| | DESC | Sort results in descending order -| STORE | _key_ | Store results in _key_ -| STOREDIST | _key_ | Store the results as distances in _key_ - - *Note*: It doesn't make sense to pass both `ASC` and `DESC` options but if both are passed the last one passed will be used. - *Note*: When using `STORE[DIST]` in Redis Cluster, the store key must has to the same slot as the query key or you will get a `CROSSLOT` error. - -###### *Return value* -*Mixed*: When no `STORE` option is passed, this function returns an array of results. If it is passed this function returns the number of stored entries. - -###### *Example* -~~~php -/* Add some cities */ -$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui"); - -echo "Within 300 miles of Honolulu:\n"; -var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi')); - -echo "\nWithin 300 miles of Honolulu with distances:\n"; -$options = ['WITHDIST']; -var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options)); - -echo "\nFirst result within 300 miles of Honolulu with distances:\n"; -$options['count'] = 1; -var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options)); - -echo "\nFirst result within 300 miles of Honolulu with distances in descending sort order:\n"; -$options[] = 'DESC'; -var_dump($redis->geoRadius("hawaii", -157.858, 21.306, 300, 'mi', $options)); -~~~ - -###### *Output* -~~~ -Within 300 miles of Honolulu: -array(2) { - [0]=> - string(8) "Honolulu" - [1]=> - string(4) "Maui" -} - -Within 300 miles of Honolulu with distances: -array(2) { - [0]=> - array(2) { - [0]=> - string(8) "Honolulu" - [1]=> - string(6) "0.0002" - } - [1]=> - array(2) { - [0]=> - string(4) "Maui" - [1]=> - string(8) "104.5615" - } -} - -First result within 300 miles of Honolulu with distances: -array(1) { - [0]=> - array(2) { - [0]=> - string(8) "Honolulu" - [1]=> - string(6) "0.0002" - } -} - -First result within 300 miles of Honolulu with distances in descending sort order: -array(1) { - [0]=> - array(2) { - [0]=> - string(4) "Maui" - [1]=> - string(8) "104.5615" - } -} -~~~ - -#### geoRadiusByMember - -###### *Prototype* -~~~php -$redis->geoRadiusByMember($key, $member, $radius, $units [, Array $options]); -~~~ - -_**Description**_: This method is identical to [geoRadius](#georadius) except that instead of passing a longitude and latitude as the "source" you pass an existing member in the geospatial set. - -###### *Options Array* -See [geoRadius](#georadius) command for options array. - -###### *Return value* -*Array*: The zero or more entries that are close enough to the member given the distance and radius specified. - -###### *Example* -~~~php -$redis->geoAdd("hawaii", -157.858, 21.306, "Honolulu", -156.331, 20.798, "Maui"); - -echo "Within 300 miles of Honolulu:\n"; -var_dump($redis->geoRadiusByMember("hawaii", "Honolulu", 300, 'mi')); - -echo "\nFirst match within 300 miles of Honolulu:\n"; -var_dump($redis->geoRadiusByMember("hawaii", "Honolulu", 300, 'mi', ['count' => 1])); -~~~ - -###### *Output* -~~~ -Within 300 miles of Honolulu: -array(2) { - [0]=> - string(8) "Honolulu" - [1]=> - string(4) "Maui" -} - -First match within 300 miles of Honolulu: -array(1) { - [0]=> - string(8) "Honolulu" -} -~~~ - -### Streams - -* [xAck](#xack) - Acknowledge one or more pending messages -* [xAdd](#xadd) - Add a message to a stream -* [xClaim](#xclaim) - Acquire ownership of a pending message -* [xDel](#xdel) - Remove a message from a stream -* [xGroup](#xgroup) - Manage consumer groups -* [xInfo](#xinfo) - Get information about a stream -* [xLen](#xlen) - Get the length of a stream -* [xPending](#xpending) - Inspect pending messages in a stream -* [xRange](#xrange) - Query a range of messages from a stream -* [xRead](#xread) - Read message(s) from a stream -* [xReadGroup](#xreadgroup) - Read stream messages with a group and consumer -* [xRevRange](#xrevrange) - Query one or more messages from end to start -* [xTrim](#xtrim) - Trim a stream's size - -#### xAck ------ - -###### *Prototype* -~~~php -$obj_redis->xAck($stream, $group, $arr_messages); -~~~ - -_**Description**_: Acknowledge one or more messages on behalf of a consumer group. - -###### *Return value* -*long*: The number of messages Redis reports as acknowledged. - -###### *Example* -~~~php -$obj_redis->xAck('stream', 'group1', ['1530063064286-0', '1530063064286-1']); -~~~ - -#### xAdd ------ - -###### *Prototype* -~~~php -$obj_redis->xAdd($str_key, $str_id, $arr_message[, $i_maxlen, $boo_approximate]); -~~~ - -_**Description**_: Add a message to a stream - -###### *Return value* -*String*: The added message ID - -###### *Example* -~~~php -$obj_redis->xAdd('mystream', "*", ['field' => 'value']); -$obj_redis->xAdd('mystream', "*", ['field' => 'value'], 1000); // set max length of stream to 1000 -$obj_redis->xAdd('mystream', "*", ['field' => 'value'], 1000, true); // set max length of stream to ~1000 -~~~ - -#### xClaim ------ - -###### *Prototype* -~~~php -$obj_redis->xClaim($str_key, $str_group, $str_consumer, $min_idle_time, $arr_ids, [$arr_options]); -~~~ - -_**Description**_: Claim ownership of one or more pending messages. - -##### *Options Array* -~~~php -$options = [ - /* Note: 'TIME', and 'IDLE' are mutually exclusive */ - 'IDLE' => $value, /* Set the idle time to $value ms */, - 'TIME' => $value, /* Set the idle time to now - $value */ - 'RETRYCOUNT' => $value, /* Update message retrycount to $value */ - 'FORCE', /* Claim the message(s) even if they're not pending anywhere */ - 'JUSTID', /* Instruct Redis to only return IDs */ -]; -~~~ - -###### *Return value* -*Array*: Either an array of message IDs along with corresponding data, or just an array of IDs (if the 'JUSTID' option was passed). - -###### *Example* -~~~php -$ids = ['1530113681011-0', '1530113681011-1', '1530113681011-2']; - -/* Without any options */ -$obj_redis->xClaim( - 'mystream', 'group1', 'myconsumer1', 0, $ids -); - -/* With options */ -$obj_redis->xClaim( - 'mystream', 'group1', 'myconsumer2', 0, $ids, - [ - 'IDLE' => time() * 1000, - 'RETRYCOUNT' => 5, - 'FORCE', - 'JUSTID' - ] -); -~~~ - -#### xDel ------ - -###### *Prototype* -~~~php -$obj_redis->xDel($str_key, $arr_ids); -~~~ - -_**Description**_: Delete one or more messages from a stream. - -###### *Return value* -*long*: The number of messages removed - -###### *Example* -~~~php -$obj_redis->xDel('mystream', ['1530115304877-0', '1530115305731-0']); -~~~ - -#### xGroup ------ - -###### *Prototype* -~~~php -$obj_redis->xGroup('HELP'); -$obj_redis->xGroup('CREATE', $str_key, $str_group, $str_msg_id, [$boo_mkstream]); -$obj_redis->xGroup('SETID', $str_key, $str_group, $str_msg_id); -$obj_redis->xGroup('DESTROY', $str_key, $str_group); -$obj_redis->xGroup('DELCONSUMER', $str_key, $str_group, $str_consumer_name); -~~~ - -_**Description**_: This command is used to create, destroy, or manage consumer groups. - -###### *Return value* -*Mixed*: This command returns different types depending on the specific XGROUP command executed. - -###### *Example* -~~~php -$obj_redis->xGroup('CREATE', 'mystream', 'mygroup', '0'); -$obj_redis->xGroup('CREATE', 'mystream', 'mygroup2', '0', true); /* Create stream if non-existent. */ -$obj_redis->xGroup('DESTROY', 'mystream', 'mygroup'); -~~~ - -#### xInfo ------ - -###### *Prototype* -~~~php -$obj_redis->xInfo('CONSUMERS', $str_stream, $str_group); -$obj_redis->xInfo('GROUPS', $str_stream); -$obj_redis->xInfo('STREAM', $str_stream [, 'FULL' [, $i_count]]); -$obj_redis->xInfo('HELP'); -~~~ - -_**Description**_: Get information about a stream or consumer groups. - -###### *Return value* -*Mixed*: This command returns different types depending on which subcommand is used. - -###### *Example* -~~~php -$obj_redis->xInfo('STREAM', 'mystream'); -$obj_redis->xInfo('STREAM', 'mystream', 'FULL', 10); -~~~ - -#### xLen ------ - -###### *Prototype* -~~~php -$obj_redis->xLen($str_stream); -~~~ - -_**Description**_: Get the length of a given stream - -###### *Return value* -*Long*: The number of messages in the stream. - -###### *Example* -~~~php -$obj_redis->xLen('mystream'); -~~~ - -#### xPending ------ - -###### *Prototype* -~~~php -$obj_redis->xPending($str_stream, $str_group [, $str_start, $str_end, $i_count, $str_consumer]); -~~~ - -_**Description**_: Get information about pending messages in a given stream. - -###### *Return value* -*Array*: Information about the pending messages, in various forms depending on the specific invocation of XPENDING. - -###### *Examples* -~~~php -$obj_redis->xPending('mystream', 'mygroup'); -$obj_redis->xPending('mystream', 'mygroup', '-', '+', 1, 'consumer-1'); -~~~ - -#### xRange ------ - -###### *Prototype* -~~~php -$obj_redis->xRange($str_stream, $str_start, $str_end [, $i_count]); -~~~ - -_**Description**_: Get a range of messages from a given stream. - -###### *Return value* -*Array*: The messages in the stream within the requested range. - -###### *Example* -~~~php -/* Get everything in this stream */ -$obj_redis->xRange('mystream', '-', '+'); - -/* Only the first two messages */ -$obj_redis->xRange('mystream', '-', '+', 2); -~~~ - -#### xRead ------ - -###### *Prototype* -~~~php -$obj_redis->xRead($arr_streams [, $i_count, $i_block]); -~~~ - -_**Description**_: Read data from one or more streams and only return IDs greater than sent in the command. - -###### *Return value* -*Array*: The messages in the stream newer than the IDs passed to Redis (if any). - -###### *Example* -~~~php -$obj_redis->xRead(['stream1' => '1535222584555-0', 'stream2' => '1535222584555-0']); - -/* --- Possible output --- -Array -( - [stream1] => Array - ( - [1535222584555-1] => Array - ( - [key:1] => val:1 - ) - - ) - - [stream2] => Array - ( - [1535222584555-1] => Array - ( - [key:1] => val:1 - ) - - ) - -) -*/ - -// Receive only new message ($ = last id) and wait for one new message unlimited time -$obj_redis->xRead(['stream1' => '$'], 1, 0); -~~~ - -#### xReadGroup ------ - -###### *Prototype* -~~~php -$obj_redis->xReadGroup($str_group, $str_consumer, $arr_streams [, $i_count, $i_block]); -~~~ - -_**Description**_: This method is similar to xRead except that it supports reading messages for a specific consumer group. - -###### *Return value* -*Array*: The messages delivered to this consumer group (if any). - -###### *Examples* -~~~php -/* Consume messages for 'mygroup', 'consumer1' */ -$obj_redis->xReadGroup('mygroup', 'consumer1', ['s1' => 0, 's2' => 0]); - -/* Consume messages for 'mygroup', 'consumer1' which were not consumed yet by the group */ -$obj_redis->xReadGroup('mygroup', 'consumer1', ['s1' => '>', 's2' => '>']); - -/* Read a single message as 'consumer2' wait for up to a second until a message arrives. */ -$obj_redis->xReadGroup('mygroup', 'consumer2', ['s1' => 0, 's2' => 0], 1, 1000); -~~~ - -#### xRevRange ------ - -###### *Prototype* -~~~php -$obj_redis->xRevRange($str_stream, $str_end, $str_start [, $i_count]); -~~~ - -_**Description**_: This is identical to xRange except the results come back in reverse order. Also note that Redis reverses the order of "start" and "end". - -###### *Return value* -*Array*: The messages in the range specified. - -###### *Example* -~~~php -$obj_redis->xRevRange('mystream', '+', '-'); -~~~ - -#### xTrim ------ - -###### *Prototype* -~~~php -$obj_redis->xTrim($str_stream, $i_max_len [, $boo_approximate]); -~~~ - -_**Description**_: Trim the stream length to a given maximum. If the "approximate" flag is passed, Redis will use your size as a hint but only trim trees in whole nodes (this is more efficient). - -###### *Return value* -*long*: The number of messages trimmed from the stream. - -###### *Example* -~~~php -/* Trim to exactly 100 messages */ -$obj_redis->xTrim('mystream', 100); - -/* Let Redis approximate the trimming */ -$obj_redis->xTrim('mystream', 100, true); -~~~ - -### Pub/sub - -* [subscribe](#subscribe) - Subscribe to channels -* [unsubscribe](#unsubscribe) - Stop listening to channels -* [pSubscribe](#psubscribe) - Subscribe to channels by pattern -* [punsubscribe](#punsubscribe) - Stop listening to pattern subscriptions -* [publish](#publish) - Post a message to a channel -* [pubSub](#pubsub) - Introspection into the pub/sub subsystem - -#### subscribe ------ -_**Description**_: Subscribe to channels. Warning: this function will probably change in the future. - -###### *Parameters* -*channels*: an array of channels to subscribe to -*callback*: either a string or [$instance, 'method_name']. The callback function receives 3 parameters: the redis instance, the channel name, and the message. -*return value*: Mixed. Any non-null return value in the callback will be returned to the caller. - -Calling `$redis->unsubscribe()` inside the callback removes the provided channels. Once all channel subscriptions have been removed (for example by omitting the parameter so every channel is removed) PhpRedis leaves pub/sub mode and returns control to your script, which is the safest way to exit a `subscribe()` loop from within the callback. - -###### *Example* -~~~php -$r = new Redis; -$r->connect('localhost', 6379); - -$r->subscribe(['channel'], function ($redis, $chan, $message) { - echo "Received {$chan}: {$message}\n"; - $redis->unsubscribe(['channel']); -}); - -echo "Done\n"; -~~~ - -#### unsubscribe ------ -_**Description**_: Remove one or more channel subscriptions. When all active channel subscriptions are removed PhpRedis exits pub/sub mode. - -###### *Parameters* -*channels*: an array of channels to unsubscribe from. Passing an empty array, or omitting the parameter while inside an active subscription loop, unsubscribes from every channel. - -###### *Return value* -*Redis|array|bool*: Outside of a subscription loop the method returns `true` on success. When invoked from within a subscription callback the method returns the server response array (`['unsubscribe', $channel, $remaining]`) until all subscriptions have been removed. - -###### *Example* -~~~php -$redis->unsubscribe(['first', 'second']); -~~~ - -#### pSubscribe ------ -_**Description**_: Subscribe to channels by pattern. Warning: this function will probably change in the future. - -###### *Parameters* -*patterns*: An array of patterns to match -*callback*: Either a string or an array with an object and method. The callback will get four arguments ($redis, $pattern, $channel, $message) -*return value*: Mixed. Any non-null return value in the callback will be returned to the caller. - -When you no longer need a pattern subscription call `$redis->punsubscribe()` from inside the callback. PhpRedis tracks the exact patterns you subscribed to and exits pub/sub mode once no patterns remain (including when the parameter is omitted to remove every pattern). - -###### *Example* -~~~php -$r = new Redis; -$r->connect('localhost', 6379); - -$r->psubscribe(['*foo*', '*bar*'], function ($redis, $pattern, $channel, $message) { - echo "Pattern {$pattern} matched {$channel}: {$message}\n"; - $redis->punsubscribe(['*foo*', '*bar*']); -}); - -echo "Done\n"; -~~~ - -#### punsubscribe ------ -_**Description**_: Remove one or more pattern subscriptions that were registered with `pSubscribe()`. - -###### *Parameters* -*patterns*: An array of patterns to unsubscribe from. - -###### *Return value* -*Redis|array|bool*: The channels that were removed. - -###### *Example* -~~~php -$redis->punsubscribe(['orders.*']); -$redis->punsubscribe(['foo', 'bar']); -$redis->punsubscribe(['*']); -~~~ - -_**Note**_: PhpRedis does not interpret glob-style requests that differ from the patterns you originally supplied to `pSubscribe()`. For example, subscribing with `['foo']` and later calling `$redis->punsubscribe(['*'])` will send the command to Redis, but PhpRedis will still think `foo` is active and will keep invoking the callback. Always pass the same concrete patterns that were used to subscribe. - -#### publish ------ -_**Description**_: Publish messages to channels. Warning: this function will probably change in the future. - -###### *Parameters* -*channel*: a channel to publish to -*message*: string - -###### *Example* -~~~php -$redis->publish('chan-1', 'hello, world!'); // send message. -~~~ - -#### pubSub ------ -_**Description**_: A command allowing you to get information on the Redis pub/sub system. - -###### *Parameters* -*keyword*: String, which can be: "channels", "numsub", or "numpat" -*argument*: Optional, variant. For the "channels" subcommand, you can pass a string pattern. For "numsub" an array of channel names. - -###### *Return value* -*CHANNELS*: Returns an array where the members are the matching channels. -*NUMSUB*: Returns a key/value array where the keys are channel names and values are their counts. -*NUMPAT*: Integer return containing the number active pattern subscriptions - -###### *Example* -~~~php -$redis->pubSub("channels"); /*All channels */ -$redis->pubSub("channels", "*pattern*"); /* Just channels matching your pattern */ -$redis->pubSub("numsub", ["chan1", "chan2"]); /*Get subscriber counts for 'chan1' and 'chan2'*/ -$redis->pubSub("numpat"); /* Get the number of pattern subscribers */ - - -~~~ - -### Generic -1. [rawCommand](#rawcommand) - Execute any generic command against the server. - -#### rawCommand ------ -_**Description**_: A method to execute any arbitrary command against the a Redis server - -###### *Parameters* -This method is variadic and takes a dynamic number of arguments of various types (string, long, double), but must be passed at least one argument (the command keyword itself). - -###### *Return value* -The return value can be various types depending on what the server itself returns. No post processing is done to the returned value and it must be handled by the client code. - -###### *Example* -```php -/* Returns: true */ -$redis->rawCommand("set", "foo", "bar"); - -/* Returns: "bar" */ -$redis->rawCommand("get", "foo"); - -/* Returns: 3 */ -$redis->rawCommand("rpush", "mylist", "one", 2, 3.5); - -/* Returns: ["one", "2", "3.5000000000000000"] */ -$redis->rawCommand("lrange", "mylist", 0, -1); -``` - -### Transactions - -1. [multi, exec, discard](#multi-exec-discard) - Enter and exit transactional mode -2. [watch, unwatch](#watch-unwatch) - Watches a key for modifications by another client. - -#### multi, exec, discard. ------ -_**Description**_: Enter and exit transactional mode. - -###### *Parameters* -(optional) `Redis::MULTI` or `Redis::PIPELINE`. Defaults to `Redis::MULTI`. A `Redis::MULTI` block of commands runs as a single transaction; a `Redis::PIPELINE` block is simply transmitted faster to the server, but without any guarantee of atomicity. `discard` cancels a transaction. - -###### *Return value* -`multi()` returns the Redis instance and enters multi-mode. Once in multi-mode, all subsequent method calls return the same object until `exec()` is called. - -###### *Example* -~~~php -$ret = $redis->multi() - ->set('key1', 'val1') - ->get('key1') - ->set('key2', 'val2') - ->get('key2') - ->exec(); - -/* -$ret == [0 => TRUE, 1 => 'val1', 2 => TRUE, 3 => 'val2']; -*/ -~~~ - -#### watch, unwatch ------ -_**Description**_: Watches a key for modifications by another client. - -If the key is modified between `WATCH` and `EXEC`, the MULTI/EXEC transaction will fail (return `FALSE`). `unwatch` cancels all the watching of all keys by this client. - -###### *Parameters* -*keys*: string for one key or array for a list of keys - -###### *Example* -~~~php -$redis->watch('x'); // or for a list of keys: $redis->watch(['x','another key']); -/* long code here during the execution of which other clients could well modify `x` */ -$ret = $redis->multi() - ->incr('x') - ->exec(); -/* -$ret = FALSE if x has been modified between the call to WATCH and the call to EXEC. -*/ -~~~ - - - -### Scripting - -* [eval](#eval) - Evaluate a LUA script serverside -* [evalSha](#evalsha) - Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself -* [script](#script) - Execute the Redis SCRIPT command to perform various operations on the scripting subsystem -* [getLastError](#getlasterror) - The last error message (if any) -* [clearLastError](#clearlasterror) - Clear the last error message - -#### eval ------ -_**Description**_: Evaluate a LUA script serverside - -###### *Parameters* -*script* string. -*args* array, optional. -*num_keys* int, optional. - -###### *Return value* -Mixed. What is returned depends on what the LUA script itself returns, which could be a scalar value (int/string), or an array. -Arrays that are returned can also contain other arrays, if that's how it was set up in your LUA script. If there is an error -executing the LUA script, the getLastError() function can tell you the message that came back from Redis (e.g. compile error). - -###### *Examples* -~~~php -$redis->eval("return 1"); // Returns an integer: 1 -$redis->eval("return {1,2,3}"); // Returns [1,2,3] -$redis->del('mylist'); -$redis->rpush('mylist','a'); -$redis->rpush('mylist','b'); -$redis->rpush('mylist','c'); -// Nested response: [1,2,3,['a','b','c']]; -$redis->eval("return {1,2,3,redis.call('lrange','mylist',0,-1)}"); -~~~ - -#### evalSha ------ -_**Description**_: Evaluate a LUA script serverside, from the SHA1 hash of the script instead of the script itself. - -In order to run this command Redis will have to have already loaded the script, -either by running it or via the SCRIPT LOAD command. - -###### *Parameters* -*script_sha* string. The sha1 encoded hash of the script you want to run. -*args* array, optional. Arguments to pass to the LUA script. -*num_keys* int, optional. The number of arguments that should go into the KEYS array, vs. the ARGV array when Redis spins the script - -###### *Return value* -Mixed. See EVAL - -###### *Examples* -~~~php -$script = 'return 1'; -$sha = $redis->script('load', $script); -$redis->evalSha($sha); // Returns 1 -~~~ - -#### script ------ -_**Description**_: Execute the Redis SCRIPT command to perform various operations on the scripting subsystem. - -###### *Usage* -~~~php -$redis->script('load', $script); -$redis->script('flush'); -$redis->script('kill'); -$redis->script('exists', $script1, [$script2, $script3, ...]); -~~~ - -###### *Return value* -* SCRIPT LOAD will return the SHA1 hash of the passed script on success, and FALSE on failure. -* SCRIPT FLUSH should always return TRUE -* SCRIPT KILL will return true if a script was killed and false if not -* SCRIPT EXISTS will return an array with TRUE or FALSE for each passed script - -#### client ------ -_**Description**_: Issue the CLIENT command with various arguments. - -The Redis CLIENT command can be used in four ways. -* CLIENT LIST -* CLIENT GETNAME -* CLIENT SETNAME [name] -* CLIENT KILL [ip:port] - -###### *Usage* -~~~php -$redis->client('list'); // Get a list of clients -$redis->client('getname'); // Get the name of the current connection -$redis->client('setname', 'somename'); // Set the name of the current connection -$redis->client('kill', ); // Kill the process at ip:port -~~~ - -###### *Return value* -This will vary depending on which client command was executed. - -* CLIENT LIST will return an array of arrays with client information. -* CLIENT GETNAME will return the client name or false if none has been set -* CLIENT SETNAME will return true if it can be set and false if not -* CLIENT KILL will return true if the client can be killed, and false if not - -Note: phpredis will attempt to reconnect so you can actually kill your own connection -but may not notice losing it! -#### getLastError +#### isConnected ----- -_**Description**_: The last error message (if any) +_**Description**_: A method to determine if a phpredis object thinks it's connected to a server ###### *Parameters* -*none* -###### *Return value* -A string with the last returned script based error message, or NULL if there is no error - -###### *Examples* -~~~php -$redis->eval('this-is-not-lua'); -$err = $redis->getLastError(); -// "ERR Error compiling script (new function): user_script:1: '=' expected near '-'" -~~~ - -#### clearLastError ------ -_**Description**_: Clear the last error message - -###### *Parameters* -*none* +None ###### *Return value* -*BOOL* TRUE - -###### *Examples* -~~~php -$redis->set('x', 'a'); -$redis->incr('x'); -$err = $redis->getLastError(); -// "ERR value is not an integer or out of range" -$redis->clearLastError(); -$err = $redis->getLastError(); -// NULL -~~~ - -### Local Helper Methods - -These helpers expose the exact logic PhpRedis uses locally for serialization, compression, and prefixing. - -* [_compress](#_compress) - Compress a string with the configured compression option -* [_uncompress](#_uncompress) - Uncompress a string with the configured compression option -* [_serialize](#_serialize) - Serialize a value with the configured serializer -* [_unserialize](#_unserialize) - Unserialize a string with the configured serializer -* [_pack](#_pack) - Serialize and compress a value exactly as PhpRedis would before sending it to Redis -* [_unpack](#_unpack) - Reverse `_pack` to retrieve the original PHP value -* [_prefix](#_prefix) - Apply the configured key prefix locally -* [_digest](#_digest) - Compute the XXH3 digest of a packed value just like Redis' DIGEST command - -#### _compress ------ -_**Description**_: Compress a string using whatever `Redis::OPT_COMPRESSION` is currently set to. This is useful when you need to mimic PhpRedis' compression logic without sending data to Redis. - -###### *Parameters* -*value* string. The string to compress. -###### *Return value* -*string* Returns the compressed string, or the original value if compression is disabled. +| Type | Description | +| --- | --- | +| `bool` | Returns TRUE if phpredis thinks it's connected and FALSE if not | -###### *Examples* -~~~php -$redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); -$payload = $redis->_compress('large-payload'); -~~~ -#### _uncompress +#### getHost ----- -_**Description**_: Reverse `_compress` by uncompressing a string with the compression option currently in use. +_**Description**_: Retrieve our host or unix socket that we're connected to ###### *Parameters* -*value* string. The raw compressed value to uncompress. - -###### *Return value* -*string* Returns the uncompressed value. Throws an exception if the payload is invalid for the configured compressor. - -###### *Examples* -~~~php -$redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZ4); -$original = $redis->_uncompress($compressedPayload); -~~~ - -#### _serialize ------ -_**Description**_: Serialize a value manually using whatever serializer is configured. - -This can be useful for serialization/unserialization of data going in and out of EVAL commands -as phpredis can't automatically do this itself. Note that if no serializer is set, phpredis -will change Array values to 'Array', and Objects to 'Object'. -###### *Parameters* -*value* mixed. The value to be serialized. +None ###### *Return value* -*string* The serialized representation of the value. - -###### *Examples* -~~~php -$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE); -$redis->_serialize("foo"); // returns "foo" -$redis->_serialize([]); // Returns "Array" -$redis->_serialize(new stdClass()); // Returns "Object" - -$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); -$redis->_serialize("foo"); // Returns 's:3:"foo";' -~~~ - -#### _unserialize ------ -_**Description**_: Unserialize a string using whatever serializer is configured. - -If there is no serializer set, the value will be returned unchanged. If there is a serializer set up, -and the data passed in is malformed, an exception will be thrown. - -###### *Parameters* -*value* string. The value to be unserialized. -###### *Return value* -*mixed* The PHP value represented by the serialized string. +| Type | Description | +| --- | --- | +| `string` | The host or unix socket we're connected to or FALSE if we're not connected | -###### *Examples* -~~~php -$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); -$redis->_unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // Will return [1,2,3] -~~~ -#### _pack +#### getPort ----- -_**Description**_: Pack a value the same way PhpRedis does internally by first serializing (if configured) and then compressing (if configured). This mirrors the exact bytes Redis receives. +_**Description**_: Get the port we're connected to ###### *Parameters* -*value* mixed. The PHP value to pack. - -###### *Return value* -*string* The packed payload that would be sent to Redis. - -###### *Examples* -~~~php -$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP); -$redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); -$payload = $redis->_pack(['a' => 1]); -~~~ - -#### _unpack ------ -_**Description**_: Reverse `_pack` by uncompressing and then unserializing a payload using the current PhpRedis options. -###### *Parameters* -*value* string. The packed payload to unpack. +None ###### *Return value* -*mixed* The unpacked PHP value. - -###### *Examples* -~~~php -$value = $redis->_unpack($payload); -~~~ - -#### _prefix ------ -_**Description**_: A utility method to prefix the value with the prefix setting for PhpRedis. - -###### *Parameters* -*value* string. The value you wish to prefix. -###### *Return value* -*string* Returns the prefixed value when a prefix is configured, or the original string otherwise. +| Type | Description | +| --- | --- | +| `int` | Returns the port we're connected to or FALSE if we're not connected | -###### *Examples* -~~~php -$redis->setOption(Redis::OPT_PREFIX, 'my-prefix:'); -$redis->_prefix('my-value'); // Will return 'my-prefix:my-value' -~~~ -#### _digest +#### getDbNum ----- -_**Description**_: Compute the XXH3 digest of a PHP value after it has been `_pack`ed. This produces the same output as Redis' `DIGEST` command, making it easy to verify values locally. +_**Description**_: Get the database number phpredis is pointed to ###### *Parameters* -*value* mixed. The PHP value to digest. - -###### *Return value* -*string* A 16 character hex string containing the XXH3 digest. - -###### *Examples* -~~~php -$digest = $redis->_digest(['foo' => 'bar']); -~~~ -### Introspection - -#### isConnected ------ -_**Description**_: A method to determine if a phpredis object thinks it's connected to a server - -###### *Parameters* None ###### *Return value* -*Boolean* Returns TRUE if phpredis thinks it's connected and FALSE if not - -#### getHost ------ -_**Description**_: Retrieve our host or unix socket that we're connected to - -###### *Parameters* -None -###### *Return value* -*Mixed* The host or unix socket we're connected to or FALSE if we're not connected +| Type | Description | +| --- | --- | +| `int` | Returns the database number (LONG) phpredis thinks it's pointing to or FALSE if we're not connected | -#### getPort +#### getTimeout ----- -_**Description**_: Get the port we're connected to +_**Description**_: Get the (write) timeout in use for phpredis ###### *Parameters* -None - -###### *Return value* -*Mixed* Returns the port we're connected to or FALSE if we're not connected - -#### getDbNum ------ -_**Description**_: Get the database number phpredis is pointed to -###### *Parameters* None ###### *Return value* -*Mixed* Returns the database number (LONG) phpredis thinks it's pointing to or FALSE if we're not connected - -#### getTimeout ------ -_**Description**_: Get the (write) timeout in use for phpredis -###### *Parameters* -None +| Type | Description | +| --- | --- | +| `float\|false` | The timeout (DOUBLE) specified in our connect call or FALSE if we're not connected | -###### *Return value* -*Mixed* The timeout (DOUBLE) specified in our connect call or FALSE if we're not connected #### getReadTimeout _**Description**_: Get the read timeout specified to phpredis or FALSE if we're not connected ###### *Parameters* + None ###### *Return value* -*Mixed* Returns the read timeout (which can be set using setOption and Redis::OPT_READ_TIMEOUT) or FALSE if we're not connected + +| Type | Description | +| --- | --- | +| `float` | Returns the read timeout (which can be set using setOption and Redis::OPT_READ_TIMEOUT) or FALSE if we're not connected | + #### getPersistentID ----- _**Description**_: Gets the persistent ID that phpredis is using ###### *Parameters* + None ###### *Return value* -*Mixed* Returns the persistent id phpredis is using (which will only be set if connected with pconnect), NULL if we're not -using a persistent ID, and FALSE if we're not connected + +| Type | Description | +| --- | --- | +| `string\|null` | Returns the persistent id phpredis is using (which will only be set if connected with pconnect), NULL if we're not using a persistent ID, and FALSE if we're not connected | + #### getAuth ----- @@ -4784,3 +938,16 @@ None #### *Return value* *Mixed* Returns NULL if no username/password are set, the password string if a password is set, and a `[username, password]` array if authenticated with a username and password. + +## API Documentation + +We automatically generate detailed and searchable API documentation for every class and method using [doctum](https://github.com/code-lts/doctum). + +[API Documentation](https://phpredis.github.io/phpredis) is available here. + +NOTE: To generate the docs yourself, you just need to have `doctum` on your path and can run + +```bash +doctum update doctum-config.php +``` + diff --git a/docs/Redis.html b/docs/Redis.html index 216f65e893..38b33ad5cc 100644 --- a/docs/Redis.html +++ b/docs/Redis.html @@ -5427,7 +5427,7 @@

Examples

- + Redis|array|false bzPopMax(string|array $key, string|int $timeout_or_key, mixed ...$extra_args)

@@ -5438,7 +5438,10 @@

POP the maximum scoring element off of one or more sorted sets, blocking up to a specified timeout if no elements are available.

Following are examples of the two main ways to call this method.

NOTE: We recommend calling this function with an array and a timeout as the other strategy -may be deprecated in future versions of PhpRedis

+may be deprecated in future versions of PhpRedis

+

Whether called with an array of keys or variadic keys and a timeout, the two +forms are functionally identical. Redis returns [key, member, score] for +the element popped, or an empty array if the timeout is reached.

Parameters

@@ -5506,7 +5509,7 @@

Examples

- + Redis|array|false bzPopMin(string|array $key, string|int $timeout_or_key, mixed ...$extra_args)

@@ -5586,7 +5589,7 @@

Examples

- + Redis|array|null|false bzmpop(float $timeout, array $keys, string $from, int $count = 1)

@@ -5669,7 +5672,7 @@

Examples

- + Redis|array|null|false zmpop(array $keys, string $from, int $count = 1)

@@ -5742,7 +5745,7 @@

Examples

- + Redis|array|null|false blmpop(float $timeout, array $keys, string $from, int $count = 1)

@@ -5822,7 +5825,7 @@

Examples

- + Redis|array|null|false lmpop(array $keys, string $from, int $count = 1)

@@ -5896,7 +5899,7 @@

Examples

- + bool clearLastError()

@@ -5954,7 +5957,7 @@

Examples

- + mixed client(string $opt, mixed ...$args)

@@ -6021,7 +6024,7 @@

Examples

- + bool close()

@@ -6072,7 +6075,7 @@

Examples

- + mixed command(string|null $opt = null, mixed ...$args)

@@ -6139,7 +6142,7 @@

Examples

- + mixed config(string $operation, array|string|null $key_or_settings = null, string|null $value = null)

@@ -6215,7 +6218,7 @@

Examples

- + bool connect(string $host, int $port = 6379, float $timeout = 0, string|null $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, array|null $context = null)

@@ -6271,7 +6274,14 @@

Parameters

An optional stream context to use when connecting. See \Redis::__construct() for more -details.

+details.

+

You can also pass authentication and TLS stream context +information through this array. When the host begins +with tls:// PhpRedis will forward any stream context +options directly to stream_socket_client(). Common +options you may wish to set include verify_peer, +verify_peer_name, peer_name, cafile, capath, +local_cert, local_pk, and passphrase.

@@ -6310,7 +6320,22 @@

Examples

printf("foo: %s\n", $foo); } catch (Exception $ex) { fprintf(STDERR, "Error: {$ex->getMessage()}\n"); -} +} + +// Provide authentication and a TLS stream context on connect. +$redis->connect('tls://redis.example.com', 6380, 1.5, null, 0, 0, [ + 'auth' => ['app-user', 'strong-password'], + 'stream' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + 'peer_name' => 'redis.example.com', + 'cafile' => '/etc/ssl/redis-ca.pem', + 'local_cert' => '/etc/ssl/client.crt', + 'local_pk' => '/etc/ssl/client.key', + ], +]); + +NOTE: `open` is an alias for `connect` and will be removed in a future version of PhpRedis. @@ -6321,7 +6346,7 @@

Examples

- + Redis|bool copy(string $src, string $dst, array|null $options = null)

@@ -6408,7 +6433,7 @@

Examples

- + Redis|int|false dbSize()

@@ -6465,7 +6490,7 @@

Examples

- + Redis|string debug(string $key)

@@ -6510,7 +6535,7 @@

Return Value

- + Redis|int|false decr(string $key, int $by = 1)

@@ -6589,7 +6614,7 @@

Examples

- + Redis|int|false decrBy(string $key, int $value)

@@ -6659,7 +6684,7 @@

Examples

- + Redis|int|false del(array|string $key, string ...$other_keys)

@@ -6732,7 +6757,7 @@

Examples

- + Redis|int|false delex(string $key, array|null $options = null)

@@ -6799,7 +6824,7 @@

Examples

- + Redis|int|false delifeq(string $key, mixed $value)

@@ -6867,7 +6892,7 @@

Examples

- + Redis|int|false delete(array|string $key, string ...$other_keys) deprecated

@@ -6942,7 +6967,7 @@

Examples

- + Redis|bool discard()

@@ -6997,7 +7022,7 @@

Examples

- + Redis|string|false dump(string $key)

@@ -7061,7 +7086,7 @@

Examples

- + Redis|string|false echo(string $str)

@@ -7123,7 +7148,7 @@

Examples

- + mixed eval(string $script, array $args = [], int $num_keys = 0)

@@ -7198,7 +7223,7 @@

Examples

- + mixed eval_ro(string $script_sha, array $args = [], int $num_keys = 0)

@@ -7278,7 +7303,7 @@

Examples

- + mixed evalsha(string $sha1, array $args = [], int $num_keys = 0)

@@ -7362,7 +7387,7 @@

Examples

- + mixed evalsha_ro(string $sha1, array $args = [], int $num_keys = 0)

@@ -7443,7 +7468,7 @@

Examples

- + Redis|array|false exec()

@@ -7520,7 +7545,7 @@

Examples

- + Redis|int|bool exists(mixed $key, mixed ...$other_keys)

@@ -7591,7 +7616,7 @@

Examples

- + Redis|bool expire(string $key, int $timeout, string|null $mode = null)

@@ -7670,7 +7695,7 @@

Examples

- + Redis|bool expireAt(string $key, int $timestamp, string|null $mode = null)

@@ -7755,7 +7780,7 @@

Examples

- + Redis|bool failover(array|null $to = null, bool $abort = false, int $timeout = 0)

@@ -7809,7 +7834,7 @@

Return Value

- + Redis|int|false expiretime(string $key)

@@ -7873,7 +7898,7 @@

Examples

- + Redis|int|false pexpiretime(string $key)

@@ -7943,7 +7968,7 @@

Examples

- + mixed fcall(string $fn, array $keys = [], array $args = [])

@@ -8016,7 +8041,7 @@

Examples

- + mixed fcall_ro(string $fn, array $keys = [], array $args = [])

@@ -8089,7 +8114,7 @@

Examples

- + Redis|bool flushAll(bool|null $sync = null)

@@ -8151,7 +8176,7 @@

Examples

- + Redis|bool flushDB(bool|null $sync = null)

@@ -8213,7 +8238,7 @@

Examples

- + Redis|bool|string|array function(string $operation, mixed ...$args)

@@ -8288,7 +8313,7 @@

Examples

- + Redis|int|false geoadd(string $key, float $lng, float $lat, string $member, mixed ...$other_triples_and_options)

@@ -8376,7 +8401,7 @@

Examples

- + Redis|float|false geodist(string $key, string $src, string $dst, string|null $unit = null)

@@ -8458,7 +8483,7 @@

Examples

- + Redis|array|false geohash(string $key, string $member, string ...$other_members)

@@ -8536,7 +8561,7 @@

Examples

- + Redis|array|false geopos(string $key, string $member, string ...$other_members)

@@ -8608,7 +8633,7 @@

Examples

- + mixed georadius(string $key, float $lng, float $lat, float $radius, string $unit, array $options = [])

@@ -8652,22 +8677,26 @@

Parameters

array $options

An array of options that modifies how the command behaves.

-
$options = [
-    'WITHCOORD',     # Return members and their coordinates.
-    'WITHDIST',      # Return members and their distances from the center.
-    'WITHHASH',      # Return members GeoHash string.
-    'ASC' | 'DESC',  # The sort order of returned members
+
                       $options = [
+                           'WITHCOORD',     # Return members and their coordinates.
+                           'WITHDIST',      # Return members and their distances from the center.
+                           'WITHHASH',      # Return members GeoHash string.
+                           'ASC' | 'DESC',  # The sort order of returned members
 
-    # Limit to N returned members.  Optionally a two element array may be
-    # passed as the `LIMIT` argument, and the `ANY` argument.
-    'COUNT' => [<int>], or [<int>, <bool>]
+                           # Limit to N returned members.  Optionally a two element array may be
+                           # passed as the `LIMIT` argument, and the `ANY` argument.
+                           'COUNT' => [<int>], or [<int>, <bool>]
 
-    # Instead of returning members, store them in the specified key.
-    'STORE' => <string>
+                           # Instead of returning members, store them in the specified key.
+                           'STORE' => <string>
 
-    # Store the distances in the specified key
-    'STOREDIST' => <string>
-];
+ # Store the distances in the specified key + 'STOREDIST' => <string> + ];
+

NOTE: When using STORE or STOREDIST in Redis Cluster, the destination key +must hash to the same slot as the query key or Redis will raise a CROSSLOT +error. If both ASC and DESC are passed, the option specified last +wins.

@@ -8712,7 +8741,7 @@

Examples

- + mixed georadius_ro(string $key, float $lng, float $lat, float $radius, string $unit, array $options = [])

@@ -8805,7 +8834,7 @@

Examples

- + mixed georadiusbymember(string $key, string $member, float $radius, string $unit, array $options = [])

@@ -8889,7 +8918,7 @@

Examples

- + mixed georadiusbymember_ro(string $key, string $member, float $radius, string $unit, array $options = [])

@@ -8971,7 +9000,7 @@

Examples

- + array geosearch(string $key, array|string $position, array|int|float $shape, string $unit, array $options = [])

@@ -9057,7 +9086,7 @@

Examples

- + Redis|array|int|false geosearchstore(string $dst, string $src, array|string $position, array|int|float $shape, string $unit, array $options = [])

@@ -9155,7 +9184,7 @@

Examples

- + mixed get(string $key)

@@ -9217,7 +9246,7 @@

Examples

- + Redis|array|false getWithMeta(string $key)

@@ -9268,7 +9297,7 @@

Examples

- + mixed getAuth()

@@ -9321,7 +9350,7 @@

Examples

- + Redis|int|false getBit(string $key, int $idx)

@@ -9388,7 +9417,7 @@

Examples

- + Redis|string|bool getEx(string $key, array $options = [])

@@ -9462,7 +9491,7 @@

Examples

- + int getDBNum()

@@ -9521,7 +9550,7 @@

Examples

- + Redis|string|bool getDel(string $key)

@@ -9583,7 +9612,7 @@

Examples

- + string getHost()

@@ -9624,7 +9653,7 @@

Examples

- + string|null getLastError()

@@ -9665,7 +9694,7 @@

Examples

- + int getMode()

@@ -9706,7 +9735,7 @@

Examples

- + mixed getOption(int $option)

@@ -9769,7 +9798,7 @@

Examples

- + string|null getPersistentID()

@@ -9810,7 +9839,7 @@

Examples

- + int getPort()

@@ -9851,7 +9880,7 @@

Examples

- + string|false serverName()

@@ -9892,7 +9921,7 @@

Examples

- + string|false serverVersion()

@@ -9933,7 +9962,7 @@

Examples

- + Redis|string|false getRange(string $key, int $start, int $end)

@@ -10006,7 +10035,7 @@

Examples

- + Redis|string|array|int|false lcs(string $key1, string $key2, array|null $options = null)

@@ -10091,7 +10120,7 @@

Examples

- + float getReadTimeout()

@@ -10132,7 +10161,7 @@

Examples

- + Redis|string|false getset(string $key, mixed $value)

@@ -10200,7 +10229,7 @@

Examples

- + float|false getTimeout()

@@ -10241,7 +10270,7 @@

Examples

- + array getTransferredBytes()

@@ -10282,7 +10311,7 @@

Examples

- + void clearTransferredBytes()

@@ -10323,7 +10352,7 @@

Examples

- + Redis|int|false hDel(string $key, string $field, string ...$other_fields)

@@ -10395,7 +10424,7 @@

Examples

- + Redis|bool hExists(string $key, string $field)

@@ -10462,7 +10491,7 @@

Examples

- + mixed hGet(string $key, string $member)

@@ -10511,7 +10540,7 @@

Return Value

- + Redis|array|false hGetAll(string $key)

@@ -10573,7 +10602,7 @@

Examples

- + mixed hGetWithMeta(string $key, string $member)

@@ -10629,7 +10658,7 @@

Examples

- + Redis|int|false hIncrBy(string $key, string $field, int $value)

@@ -10702,7 +10731,7 @@

Examples

- + Redis|float|false hIncrByFloat(string $key, string $field, float $value)

@@ -10774,7 +10803,7 @@

Examples

- + Redis|array|false hKeys(string $key)

@@ -10836,7 +10865,7 @@

Examples

- + Redis|int|false hLen(string $key)

@@ -10898,7 +10927,7 @@

Examples

- + Redis|array|false hMget(string $key, array $fields)

@@ -10965,7 +10994,7 @@

Examples

- + Redis|array|false hgetex(string $key, array $fields, string|array|null $expiry = null)

@@ -11038,7 +11067,7 @@

Examples

- + Redis|int|false hsetex(string $key, array $fields, array|null $expiry = null)

@@ -11110,7 +11139,7 @@

Examples

- + Redis|array|false hgetdel(string $key, array $fields)

@@ -11177,7 +11206,7 @@

Examples

- + Redis|bool hMset(string $key, array $fieldvals)

@@ -11244,7 +11273,7 @@

Examples

- + Redis|string|array|false hRandField(string $key, array|null $options = null)

@@ -11318,7 +11347,7 @@

Examples

- + Redis|int|false hSet(string $key, mixed ...$fields_and_vals)

@@ -11389,7 +11418,7 @@

Examples

- + Redis|bool hSetNx(string $key, string $field, mixed $value)

@@ -11462,7 +11491,7 @@

Examples

- + Redis|int|false hStrLen(string $key, string $field)

@@ -11532,7 +11561,7 @@

Examples

- + Redis|array|false hVals(string $key)

@@ -11594,7 +11623,7 @@

Examples

- + Redis|array|false hexpire(string $key, int $ttl, array $fields, string|null $mode = NULL)

@@ -11671,7 +11700,7 @@

Examples

- + Redis|array|false hpexpire(string $key, int $ttl, array $fields, string|null $mode = NULL)

@@ -11748,7 +11777,7 @@

Examples

- + Redis|array|false hexpireat(string $key, int $time, array $fields, string|null $mode = NULL)

@@ -11825,7 +11854,7 @@

Examples

- + Redis|array|false hpexpireat(string $key, int $mstime, array $fields, string|null $mode = NULL)

@@ -11902,7 +11931,7 @@

Examples

- + Redis|array|false httl(string $key, array $fields)

@@ -11969,7 +11998,7 @@

Examples

- + Redis|array|false hpttl(string $key, array $fields)

@@ -12036,7 +12065,7 @@

Examples

- + Redis|array|false hexpiretime(string $key, array $fields)

@@ -12103,7 +12132,7 @@

Examples

- + Redis|array|false hpexpiretime(string $key, array $fields)

@@ -12170,7 +12199,7 @@

Examples

- + Redis|array|false hpersist(string $key, array $fields)

@@ -12237,7 +12266,7 @@

Examples

- + Redis|array|bool hscan(string $key, null|int|string $iterator, string|null $pattern = null, int $count = 0)

@@ -12341,7 +12370,7 @@

Examples

- + Redis|int|false expiremember(string $key, string $field, int $ttl, string|null $unit = null)

@@ -12424,7 +12453,7 @@

Examples

- + Redis|int|false expirememberat(string $key, string $field, int $timestamp)

@@ -12502,7 +12531,7 @@

Examples

- + Redis|int|false incr(string $key, int $by = 1)

@@ -12578,7 +12607,7 @@

Examples

- + Redis|int|false incrBy(string $key, int $value)

@@ -12649,7 +12678,7 @@

Examples

- + Redis|float|false incrByFloat(string $key, float $value)

@@ -12717,7 +12746,7 @@

Examples

- + Redis|array|false info(string ...$sections)

@@ -12782,7 +12811,7 @@

Examples

- + bool isConnected()

@@ -12823,7 +12852,7 @@

Examples

- + Redis|list&lt;string&gt;|false keys(string $pattern)

@@ -12886,7 +12915,7 @@

Examples

- + Redis|int|false lInsert(string $key, string $pos, mixed $pivot, mixed $value)

@@ -12964,7 +12993,7 @@

Examples

- + Redis|int|false lLen(string $key)

@@ -13026,7 +13055,7 @@

Examples

- + Redis|string|false lMove(string $src, string $dst, string $wherefrom, string $whereto)

@@ -13110,7 +13139,7 @@

Examples

- + Redis|string|false blmove(string $src, string $dst, string $wherefrom, string $whereto, float $timeout)

@@ -13174,7 +13203,7 @@

Return Value

- + Redis|bool|string|array lPop(string $key, int $count = 0)

@@ -13245,7 +13274,7 @@

Examples

- + Redis|null|bool|int|array lPos(string $key, mixed $value, array|null $options = null)

@@ -13332,7 +13361,7 @@

Examples

- + Redis|int|false lPush(string $key, mixed ...$elements)

@@ -13399,7 +13428,7 @@

Examples

- + Redis|int|false rPush(string $key, mixed ...$elements)

@@ -13466,7 +13495,7 @@

Examples

- + Redis|int|false lPushx(string $key, mixed $value)

@@ -13533,7 +13562,7 @@

Examples

- + Redis|int|false rPushx(string $key, mixed $value)

@@ -13600,7 +13629,7 @@

Examples

- + Redis|bool lSet(string $key, int $index, mixed $value)

@@ -13672,7 +13701,7 @@

Examples

- + int lastSave()

@@ -13724,7 +13753,7 @@

Examples

- + mixed lindex(string $key, int $index)

@@ -13791,7 +13820,7 @@

Examples

- + Redis|array|false lrange(string $key, int $start, int $end)

@@ -13868,7 +13897,7 @@

Examples

- + Redis|int|false lrem(string $key, mixed $value, int $count = 0)

@@ -13940,7 +13969,7 @@

Examples

- + Redis|bool ltrim(string $key, int $start, int $end)

@@ -14012,7 +14041,7 @@

Examples

- + Redis|array|false mget(array $keys)

@@ -14074,7 +14103,7 @@

Examples

- + Redis|bool migrate(string $host, int $port, string|array $key, int $dstdb, int $timeout, bool $copy = false, bool $replace = false, mixed $credentials = null)

@@ -14169,7 +14198,10 @@

Examples

$redis->set('foo', '6379_key'); // Move the key to localhost:9999 with a 5 second timeout -var_dump($redis->migrate('localhost', 9999, 'foo', 0, 5000)); +var_dump($redis->migrate('localhost', 9999, 'foo', 0, 5000)); + +// Migrate multiple keys (Redis >= 3.0.6) +$redis->migrate('backup', 6379, ['key1', 'key2', 'key3'], 0, 3600); @@ -14180,7 +14212,7 @@

Examples

- + Redis|bool move(string $key, int $index)

@@ -14247,7 +14279,7 @@

Examples

- + Redis|bool mset(array $key_values)

@@ -14309,7 +14341,7 @@

Examples

- + Redis|int|false msetex(array $key_vals, int|float|array|null $expiry = null)

@@ -14376,7 +14408,7 @@

Examples

- + Redis|bool msetnx(array $key_values)

@@ -14438,7 +14470,7 @@

Examples

- + bool|Redis multi(int $value = Redis::MULTI)

@@ -14504,7 +14536,7 @@

Examples

- + Redis|int|string|false object(string $subcommand, string $key)

@@ -14562,7 +14594,7 @@

Examples

- + bool open(string $host, int $port = 6379, float $timeout = 0, string|null $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, array|null $context = null) deprecated

@@ -14651,7 +14683,7 @@

Examples

- + bool pconnect(string $host, int $port = 6379, float $timeout = 0, string|null $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, array|null $context = null)

@@ -14659,7 +14691,10 @@

-

Connects to a Redis server creating or reusing a persistent connection.

+

Connects to a Redis server creating or reusing a persistent connection.

Persistent connections remain open until the PHP process ends so take care to +avoid exhausting file descriptors if you create many of them. As of PhpRedis +4.2.1 you can enable connection pooling with the INI directive +redis.pconnect.pooling_enabled=1 (not supported in threaded builds).

Parameters

@@ -14733,9 +14768,12 @@

Examples

try {
     $redis = new Redis();
     $redis->pconnect('localhost', 6379);
+    $redis->pconnect('tls://localhost', 6379, 2.5, 'tls');
 } catch (Exception $ex) {
    echo "Could not connect to Redis: ", $ex->getMessage(), "\n";
-}
+} + +NOTE: `popen` is an alias for `pconnect` and will be removed in a future version of PhpRedis. @@ -14746,7 +14784,7 @@

Examples

- + Redis|bool persist(string $key)

@@ -14808,7 +14846,7 @@

Examples

- + bool pexpire(string $key, int $timeout, string|null $mode = null)

@@ -14889,7 +14927,7 @@

Examples

- + Redis|bool pexpireAt(string $key, int $timestamp, string|null $mode = null)

@@ -14974,7 +15012,7 @@

Examples

- + Redis|int pfadd(string $key, array $elements)

@@ -15041,7 +15079,7 @@

Examples

- + Redis|int|false pfcount(array|string $key_or_keys)

@@ -15103,7 +15141,7 @@

Examples

- + Redis|bool pfmerge(string $dst, array $srckeys)

@@ -15170,7 +15208,7 @@

Examples

- + Redis|string|bool ping(string|null $message = null)

@@ -15236,7 +15274,7 @@

Examples

- + bool|Redis pipeline()

@@ -15284,7 +15322,7 @@

Examples

- + bool popen(string $host, int $port = 6379, float $timeout = 0, string|null $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, array|null $context = null) deprecated

@@ -15373,7 +15411,7 @@

Examples

- + Redis|bool psetex(string $key, int $expire, mixed $value)

@@ -15445,7 +15483,7 @@

Examples

- + bool psubscribe(array $patterns, callable $cb)

@@ -15515,7 +15553,7 @@

Examples

- + Redis|int|false pttl(string $key)

@@ -15579,7 +15617,7 @@

Examples

- + Redis|int|false publish(string $channel, string $message)

@@ -15646,7 +15684,7 @@

Examples

- + mixed pubsub(string $command, mixed $arg = null)

@@ -15713,7 +15751,7 @@

Examples

- + Redis|array|bool punsubscribe(array $patterns)

@@ -15788,7 +15826,7 @@

Examples

- + Redis|array|string|bool rPop(string $key, int $count = 0)

@@ -15859,7 +15897,7 @@

Examples

- + Redis|string|false randomKey()

@@ -15911,7 +15949,7 @@

Examples

- + mixed rawcommand(string $command, mixed ...$args)

@@ -15973,7 +16011,7 @@

Examples

- + Redis|bool rename(string $old_name, string $new_name)

@@ -16040,7 +16078,7 @@

Examples

- + Redis|bool renameNx(string $key_src, string $key_dst)

@@ -16111,7 +16149,7 @@

Examples

- + Redis|bool reset()

@@ -16163,7 +16201,7 @@

Examples

- + Redis|bool restore(string $key, int $ttl, string $value, array|null $options = null)

@@ -16269,7 +16307,7 @@

Examples

- + mixed role()

@@ -16322,7 +16360,7 @@

Examples

- + Redis|string|false rpoplpush(string $srckey, string $dstkey)

@@ -16396,7 +16434,7 @@

Examples

- + Redis|int|false sAdd(string $key, mixed $value, mixed ...$other_values)

@@ -16471,7 +16509,7 @@

Examples

- + int sAddArray(string $key, array $values)

@@ -16548,7 +16586,7 @@

Examples

- + Redis|array|false sDiff(string $key, string ...$other_keys)

@@ -16624,7 +16662,7 @@

Examples

- + Redis|int|false sDiffStore(string $dst, string $key, string ...$other_keys)

@@ -16703,7 +16741,7 @@

Examples

- + Redis|array|false sInter(array|string $key, string ...$other_keys)

@@ -16778,7 +16816,7 @@

Examples

- + Redis|int|false sintercard(array $keys, int $limit = -1)

@@ -16850,7 +16888,7 @@

Examples

- + Redis|int|false sInterStore(array|string $key, string ...$other_keys)

@@ -16928,7 +16966,7 @@

Examples

- + Redis|array|false sMembers(string $key)

@@ -16991,7 +17029,7 @@

Examples

- + Redis|array|false sMisMember(string $key, string $member, string ...$other_members)

@@ -17077,7 +17115,7 @@

Examples

- + Redis|bool sMove(string $src, string $dst, mixed $value)

@@ -17153,7 +17191,7 @@

Examples

- + Redis|string|array|false sPop(string $key, int $count = 0)

@@ -17187,7 +17225,10 @@

Return Value

- +
Redis|string|array|false

When called without a count, returns a single member +or false if the set is empty. When a count is provided, +returns an array of members (which may be empty if the set +does not exist) or false on error.

@@ -17212,7 +17253,9 @@

Examples

$redis->del('numbers', 'evens');
 $redis->sAdd('numbers', 'zero', 'one', 'two', 'three', 'four');
-$redis->sPop('numbers');
+$redis->sPop('numbers'); +$redis->sAdd('letters', 'a', 'b', 'c'); +$redis->sPop('letters', 3); // Return up to three members. @@ -17223,7 +17266,7 @@

Examples

- + mixed sRandMember(string $key, int $count = 0)

@@ -17301,7 +17344,7 @@

Examples

- + Redis|array|false sUnion(string $key, string ...$other_keys)

@@ -17368,7 +17411,7 @@

Examples

- + Redis|int|false sUnionStore(string $dst, string $key, string ...$other_keys)

@@ -17447,7 +17490,7 @@

Examples

- + Redis|bool save()

@@ -17506,7 +17549,7 @@

Examples

- + array|false scan(null|int|string $iterator, string|null $pattern = null, int $count = 0, string|null $type = null)

@@ -17629,7 +17672,7 @@

Examples

- + Redis|int|false scard(string $key)

@@ -17691,7 +17734,7 @@

Examples

- + mixed script(string $command, mixed ...$args)

@@ -17761,7 +17804,7 @@

Examples

- + Redis|bool select(int $db)

@@ -17823,7 +17866,7 @@

Examples

- + Redis|string|bool set(string $key, mixed $value, mixed $options = null)

@@ -17917,7 +17960,7 @@

Examples

- + Redis|int|false setBit(string $key, int $idx, bool $value)

@@ -17990,7 +18033,7 @@

Examples

- + Redis|int|false setRange(string $key, int $index, string $value)

@@ -18063,7 +18106,7 @@

Examples

- + bool setOption(int $option, mixed $value)

@@ -18089,7 +18132,7 @@

OPT_SCAN enum -Redis::OPT_SCAN_RETRY, or Redis::OPT_SCAN_NORETRY. Whether PhpRedis should automatically SCAN again when zero keys but a nonzero iterator are returned. +Redis::SCAN_RETRY
Redis::SCAN_NORETRY. OPT_SERIALIZER @@ -18134,7 +18177,7 @@

OPT_BACKOFF_ALGORITHM enum -The exponential backoff strategy to use. +The exponential backoff strategy to use. Specifically Redis::BACKOFF_ALGORITHM_* OPT_BACKOFF_BASE @@ -18203,7 +18246,14 @@

Examples

- +
$redis->setOption(Redis::OPT_PREFIX, 'app:');
$redis->setOption(Redis::OPT_PREFIX, 'app:');
+$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
+
+// Configure SCAN behaviour.
+$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY);
+$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
+$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_PREFIX);
+$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NOPREFIX);
@@ -18214,7 +18264,7 @@

Examples

- + Redis|bool setex(string $key, int $expire, mixed $value)

@@ -18286,7 +18336,7 @@

Examples

- + Redis|bool setnx(string $key, mixed $value)

@@ -18356,7 +18406,7 @@

Examples

- + Redis|bool sismember(string $key, mixed $value)

@@ -18423,7 +18473,7 @@

Examples

- + Redis|bool slaveof(string|null $host = null, int $port = 6379) deprecated

@@ -18515,7 +18565,7 @@

Examples

- + Redis|bool replicaof(string|null $host = null, int $port = 6379)

@@ -18604,7 +18654,7 @@

Examples

- + Redis|int|false touch(array|string $key_or_array, string ...$more_keys)

@@ -18673,7 +18723,7 @@

Examples

- + mixed slowlog(string $operation, int $length = 0)

@@ -18755,7 +18805,7 @@

Examples

- + mixed sort(string $key, array|null $options = null)

@@ -18836,7 +18886,7 @@

Examples

- + mixed sort_ro(string $key, array|null $options = null)

@@ -18910,7 +18960,7 @@

Examples

- + array sortAsc(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

@@ -19005,7 +19055,7 @@

Examples

- + array sortAscAlpha(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

@@ -19100,7 +19150,7 @@

Examples

- + array sortDesc(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

@@ -19195,7 +19245,7 @@

Examples

- + array sortDescAlpha(string $key, string|null $pattern = null, mixed $get = null, int $offset = -1, int $count = -1, string|null $store = null) deprecated

@@ -19290,7 +19340,7 @@

Examples

- + Redis|int|false srem(string $key, mixed $value, mixed ...$other_values)

@@ -19362,7 +19412,7 @@

Examples

- + array|false sscan(string $key, null|int|string $iterator, string|null $pattern = null, int $count = 0)

@@ -19492,7 +19542,7 @@

Examples

- + bool ssubscribe(array $channels, callable $cb)

@@ -19575,7 +19625,7 @@

Examples

- + Redis|int|false strlen(string $key)

@@ -19638,7 +19688,7 @@

Examples

- + bool subscribe(array $channels, callable $cb)

@@ -19721,7 +19771,7 @@

Examples

- + Redis|array|bool sunsubscribe(array $channels)

@@ -19800,7 +19850,7 @@

Examples

- + Redis|bool swapdb(int $src, int $dst)

@@ -19879,7 +19929,7 @@

Examples

- + Redis|array time()

@@ -19932,7 +19982,7 @@

Examples

- + Redis|int|false ttl(string $key)

@@ -19996,7 +20046,7 @@

Examples

- + Redis|int|false type(string $key)

@@ -20069,7 +20119,7 @@

Examples

@@ -20156,7 +20206,7 @@

Examples

- + Redis|array|bool unsubscribe(array $channels)

@@ -20234,7 +20284,7 @@

Examples

- + Redis|bool unwatch()

@@ -20299,7 +20349,7 @@

Examples

- + Redis|bool watch(array|string $key, string ...$other_keys)

@@ -20396,7 +20446,7 @@

Examples

- + int|false wait(int $numreplicas, int $timeout)

@@ -20464,7 +20514,7 @@

Examples

- + int|false xack(string $key, string $group, array $ids)

@@ -20572,7 +20622,7 @@

Examples

- + Redis|string|false xadd(string $key, string $id, array $values, int $maxlen = 0, bool $approx = false, bool $nomkstream = false)

@@ -20669,7 +20719,7 @@

Examples

- + Redis|bool|array xautoclaim(string $key, string $group, string $consumer, int $min_idle, string $start, int $count = -1, bool $justid = false)

@@ -20789,7 +20839,7 @@

Examples

- + Redis|array|bool xclaim(string $key, string $group, string $consumer, int $min_idle, array $ids, array $options)

@@ -20917,7 +20967,7 @@

Examples

- + Redis|int|false xdel(string $key, array $ids)

@@ -20984,7 +21034,7 @@

Examples

- + Relay|array|false xdelex(string $key, array $ids, string|null $mode = null)

@@ -21059,7 +21109,7 @@

Examples

- + mixed xgroup(string $operation, string|null $key = null, string|null $group = null, string|null $id_or_consumer = null, bool $mkstream = false, int $entries_read = -2)

@@ -21165,7 +21215,7 @@

Examples

- + mixed xinfo(string $operation, string|null $arg1 = null, string|null $arg2 = null, int $count = -1)

@@ -21248,7 +21298,7 @@

Examples

- + Redis|int|false xlen(string $key)

@@ -21310,7 +21360,7 @@

Examples

- + Redis|array|false xpending(string $key, string $group, string|null $start = null, string|null $end = null, int $count = -1, string|null $consumer = null)

@@ -21404,7 +21454,7 @@

Examples

- + Redis|array|bool xrange(string $key, string $start, string $end, int $count = -1)

@@ -21484,7 +21534,7 @@

Examples

- + Redis|array|bool xread(array $streams, int $count = -1, int $block = -1)

@@ -21564,7 +21614,7 @@

Examples

- + Redis|array|bool xreadgroup(string $group, string $consumer, array $streams, int $count = 1, int $block = 1)

@@ -21663,7 +21713,7 @@

Examples

- + Redis|array|bool xrevrange(string $key, string $end, string $start, int $count = -1)

@@ -21749,7 +21799,7 @@

Examples

- + Redis|int|false vadd(string $key, array $values, mixed $element, array|null $options = null)

@@ -21826,7 +21876,7 @@

Examples

- + Redis|array|false vsim(string $key, mixed $member, array|null $options = null)

@@ -21903,7 +21953,7 @@

Examples

- + Redis|int|false vcard(string $key)

@@ -21965,7 +22015,7 @@

Examples

- + Redis|int|false vdim(string $key)

@@ -22027,7 +22077,7 @@

Examples

- + Redis|array|false vinfo(string $key)

@@ -22089,7 +22139,7 @@

Examples

- + Redis|bool vismember(string $key, mixed $member)

@@ -22156,7 +22206,7 @@

Examples

- + Redis|array|false vemb(string $key, mixed $member, bool $raw = false)

@@ -22228,7 +22278,7 @@

Examples

- + Redis|array|string|false vrandmember(string $key, int $count = 0)

@@ -22295,7 +22345,7 @@

Examples

- + Redis|array|false vrange(string $key, string $min, string $max, int $count = -1)

@@ -22372,7 +22422,7 @@

Examples

- + Redis|int|false vrem(string $key, mixed $member)

@@ -22439,7 +22489,7 @@

Examples

- + Redis|int|false vsetattr(string $key, mixed $member, array|string $attributes)

@@ -22513,7 +22563,7 @@

Examples

- + Redis|array|string|false vgetattr(string $key, mixed $member, bool $decode = true)

@@ -22585,7 +22635,7 @@

Examples

@@ -22657,7 +22707,7 @@

Examples

- + Redis|int|false xtrim(string $key, string $threshold, bool $approx = false, bool $minid = false, int $limit = -1)

@@ -22746,7 +22796,7 @@

Examples

- + Redis|int|float|false zAdd(string $key, array|float $score_or_options, mixed ...$more_scores_and_mems)

@@ -22840,7 +22890,7 @@

Examples

- + Redis|int|false zCard(string $key)

@@ -22902,7 +22952,7 @@

Examples

- + Redis|int|false zCount(string $key, int|string $start, int|string $end)

@@ -22978,7 +23028,7 @@

Examples

- + Redis|float|false zIncrBy(string $key, float $value, mixed $member)

@@ -23051,7 +23101,7 @@

Examples

- + Redis|int|false zLexCount(string $key, string $min, string $max)

@@ -23125,7 +23175,7 @@

Examples

- + Redis|array|false zMscore(string $key, mixed $member, mixed ...$other_members)

@@ -23200,7 +23250,7 @@

Examples

- + Redis|array|false zPopMax(string $key, int|null $count = null)

@@ -23270,7 +23320,7 @@

Examples

- + Redis|array|false zPopMin(string $key, int|null $count = null)

@@ -23340,7 +23390,7 @@

Examples

- + Redis|array|false zRange(string $key, string|int $start, string|int $end, array|bool|null $options = null)

@@ -23429,7 +23479,7 @@

Examples

- + Redis|array|false zRangeByLex(string $key, string $min, string $max, int $offset = -1, int $count = -1)

@@ -23515,7 +23565,7 @@

Examples

- + Redis|array|false zRangeByScore(string $key, string $start, string $end, array $options = [])

@@ -23550,7 +23600,10 @@

Parameters

Options that change how Redis will execute the command.

OPTION TYPE MEANING 'WITHSCORES' bool Whether to also return scores. -'LIMIT' [offset, count] Limit the reply to a subset of elements.

+'LIMIT' [offset, count] Limit the reply to a subset of elements.

+

In addition to numeric scores you may pass '-inf' and '+inf' to +select all elements greater than or equal to/less than or equal to +the provided bound.

@@ -23596,7 +23649,7 @@

Examples

- + Redis|int|false zrangestore(string $dstkey, string $srckey, string $start, string $end, array|bool|null $options = null)

@@ -23685,7 +23738,7 @@

Examples

- + Redis|string|array zRandMember(string $key, array|null $options = null)

@@ -23755,7 +23808,7 @@

Examples

- + Redis|int|false zRank(string $key, mixed $member)

@@ -23823,7 +23876,7 @@

Examples

- + Redis|int|false zRem(mixed $key, mixed $member, mixed ...$other_members)

@@ -23895,7 +23948,7 @@

Examples

- + Redis|int|false zRemRangeByLex(string $key, string $min, string $max)

@@ -23974,7 +24027,7 @@

Examples

- + Redis|int|false zRemRangeByRank(string $key, int $start, int $end)

@@ -24046,7 +24099,7 @@

Examples

- + Redis|int|false zRemRangeByScore(string $key, string $start, string $end)

@@ -24119,7 +24172,7 @@

Examples

- + Redis|array|false zRevRange(string $key, int $start, int $end, mixed $scores = null)

@@ -24201,7 +24254,7 @@

Examples

- + Redis|array|false zRevRangeByLex(string $key, string $max, string $min, int $offset = -1, int $count = -1)

@@ -24290,7 +24343,7 @@

Examples

- + Redis|array|false zRevRangeByScore(string $key, string $max, string $min, array|bool $options = [])

@@ -24381,7 +24434,7 @@

Examples

- + Redis|int|false zRevRank(string $key, mixed $member)

@@ -24452,7 +24505,7 @@

Examples

- + Redis|float|false zScore(string $key, mixed $member)

@@ -24520,7 +24573,7 @@

Examples

- + Redis|array|false zdiff(array $keys, array|null $options = null)

@@ -24593,7 +24646,7 @@

Examples

- + Redis|int|false zdiffstore(string $dst, array $keys)

@@ -24668,7 +24721,7 @@

Examples

- + Redis|array|false zinter(array $keys, array|null $weights = null, array|null $options = null)

@@ -24747,7 +24800,7 @@

Examples

- + Redis|int|false zintercard(array $keys, int $limit = -1)

@@ -24833,7 +24886,7 @@

Examples

- + Redis|int|false zinterstore(string $dst, array $keys, array|null $weights = null, string|null $aggregate = null)

@@ -24924,7 +24977,7 @@

Examples

- + Redis|array|false zscan(string $key, null|int|string $iterator, string|null $pattern = null, int $count = 0)

@@ -25024,7 +25077,7 @@

Examples

- + Redis|array|false zunion(array $keys, array|null $weights = null, array|null $options = null)

@@ -25114,7 +25167,7 @@

Examples

- + Redis|int|false zunionstore(string $dst, array $keys, array|null $weights = null, string|null $aggregate = null)

@@ -25203,7 +25256,7 @@

Examples

- + Redis|string|false digest(string $key)

diff --git a/docs/renderer.index b/docs/renderer.index index 463239f727..aa6f7c9c5a 100644 --- a/docs/renderer.index +++ b/docs/renderer.index @@ -1 +1 @@ -O:21:"Doctum\Renderer\Index":3:{i:0;a:6:{s:5:"Redis";s:40:"c13469df88b1bee8129ccab19c2f18a44e545203";s:10:"RedisArray";s:40:"2a50f02b4f62d96a18ec122fec35bd6e03bf735a";s:12:"RedisCluster";s:40:"7e9d3dfcff35ee57a08e11e78e30b24a58d7d008";s:21:"RedisClusterException";s:40:"7e9d3dfcff35ee57a08e11e78e30b24a58d7d008";s:14:"RedisException";s:40:"c13469df88b1bee8129ccab19c2f18a44e545203";s:13:"RedisSentinel";s:40:"ca40579af888c5bb0661cd0201d840297474479a";}i:1;a:1:{i:0;s:7:"develop";}i:2;a:1:{i:0;s:0:"";}} \ No newline at end of file +O:21:"Doctum\Renderer\Index":3:{i:0;a:6:{s:5:"Redis";s:40:"432c8c1975766d1dcd2484187e2bfe640dabeaca";s:10:"RedisArray";s:40:"2a50f02b4f62d96a18ec122fec35bd6e03bf735a";s:12:"RedisCluster";s:40:"7e9d3dfcff35ee57a08e11e78e30b24a58d7d008";s:21:"RedisClusterException";s:40:"7e9d3dfcff35ee57a08e11e78e30b24a58d7d008";s:14:"RedisException";s:40:"432c8c1975766d1dcd2484187e2bfe640dabeaca";s:13:"RedisSentinel";s:40:"ca40579af888c5bb0661cd0201d840297474479a";}i:1;a:1:{i:0;s:7:"develop";}i:2;a:1:{i:0;s:0:"";}} \ No newline at end of file diff --git a/redis.stub.php b/redis.stub.php index e12fd944f9..03713dec77 100644 --- a/redis.stub.php +++ b/redis.stub.php @@ -924,6 +924,10 @@ public function brpoplpush(string $src, string $dst, int|float $timeout): Redis| * **NOTE**: We recommend calling this function with an array and a timeout as the other strategy * may be deprecated in future versions of PhpRedis * + * Whether called with an array of keys or variadic keys and a timeout, the two + * forms are functionally identical. Redis returns `[key, member, score]` for + * the element popped, or an empty array if the timeout is reached. + * * @see https://redis.io/docs/latest/commands/bzpopmax/ * * @param string|array $key Either a string key or an array of one or more keys. @@ -1138,6 +1142,14 @@ public function config(string $operation, array|string|null $key_or_settings = n * when connecting. * See `\Redis::__construct()` for more * details. + * + * You can also pass authentication and TLS stream context + * information through this array. When the `host` begins + * with `tls://` PhpRedis will forward any `stream` context + * options directly to `stream_socket_client()`. Common + * options you may wish to set include `verify_peer`, + * `verify_peer_name`, `peer_name`, `cafile`, `capath`, + * `local_cert`, `local_pk`, and `passphrase`. * @return bool Whether the connection was successful. * * @throws RedisException On connection errors. @@ -1151,6 +1163,21 @@ public function config(string $operation, array|string|null $key_or_settings = n * } catch (Exception $ex) { * fprintf(STDERR, "Error: {$ex->getMessage()}\n"); * } + * + * // Provide authentication and a TLS stream context on connect. + * $redis->connect('tls://redis.example.com', 6380, 1.5, null, 0, 0, [ + * 'auth' => ['app-user', 'strong-password'], + * 'stream' => [ + * 'verify_peer' => true, + * 'verify_peer_name' => true, + * 'peer_name' => 'redis.example.com', + * 'cafile' => '/etc/ssl/redis-ca.pem', + * 'local_cert' => '/etc/ssl/client.crt', + * 'local_pk' => '/etc/ssl/client.key', + * ], + * ]); + * + * NOTE: `open` is an alias for `connect` and will be removed in a future version of PhpRedis. */ public function connect(string $host, int $port = 6379, float $timeout = 0, ?string $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, ?array $context = null): bool; @@ -1749,6 +1776,11 @@ public function geopos(string $key, string $member, string ...$other_members): R * ]; * ``` * + * NOTE: When using `STORE` or `STOREDIST` in Redis Cluster, the destination key + * must hash to the same slot as the query key or Redis will raise a CROSSLOT + * error. If both `ASC` and `DESC` are passed, the option specified last + * wins. + * * @return mixed This command can return various things, depending on the options passed. * * @see https://redis.io/docs/latest/commands/georadius/ @@ -3057,6 +3089,9 @@ public function mget(array $keys): Redis|array|false; * * // Move the key to localhost:9999 with a 5 second timeout * var_dump($redis->migrate('localhost', 9999, 'foo', 0, 5000)); + * + * // Migrate multiple keys (Redis >= 3.0.6) + * $redis->migrate('backup', 6379, ['key1', 'key2', 'key3'], 0, 3600); */ public function migrate(string $host, int $port, string|array $key, int $dstdb, int $timeout, bool $copy = false, bool $replace = false, @@ -3161,6 +3196,11 @@ public function open(string $host, int $port = 6379, float $timeout = 0, ?string /** * Connects to a Redis server creating or reusing a persistent connection. * + * Persistent connections remain open until the PHP process ends so take care to + * avoid exhausting file descriptors if you create many of them. As of PhpRedis + * 4.2.1 you can enable connection pooling with the INI directive + * `redis.pconnect.pooling_enabled=1` (not supported in threaded builds). + * * @param string $host The Redis server hostname. * @param int $port The Redis server port. * @param float $timeout Connection timeout in seconds. @@ -3177,9 +3217,12 @@ public function open(string $host, int $port = 6379, float $timeout = 0, ?string * try { * $redis = new Redis(); * $redis->pconnect('localhost', 6379); + * $redis->pconnect('tls://localhost', 6379, 2.5, 'tls'); * } catch (Exception $ex) { * echo "Could not connect to Redis: ", $ex->getMessage(), "\n"; * } + * + * NOTE: `popen` is an alias for `pconnect` and will be removed in a future version of PhpRedis. */ public function pconnect(string $host, int $port = 6379, float $timeout = 0, ?string $persistent_id = null, int $retry_interval = 0, float $read_timeout = 0, ?array $context = null): bool; @@ -3318,6 +3361,28 @@ public function ping(?string $message = null): Redis|string|bool; * ->del('mylist') * ->rpush('mylist', 'a', 'b', 'c') * ->exec(); + * + * @example + * // It is also possible to nest MULTI inside a PIPELINE + * $res = $redis->pipeline() + * ->multi()->incr('t1:1')->incr('t1:2')->exec() + * ->multi()->incr('t2:1')->incr('t2:2')->exec() + * ->exec(); + * + * print_r($res); + * // Array + * // ( + * // [0] => Array + * // ( + * // [0] => 4 + * // [1] => 2 + * // ) + * // + * // [1] => Array + * // ( + * // [0] => 2 + * // [1] => 4 + * // ) */ public function pipeline(): bool|Redis; @@ -3805,10 +3870,17 @@ public function sMove(string $src, string $dst, mixed $value): Redis|bool; * @param int $count An optional number of members to pop. This defaults to * removing one element. * + * @return Redis|string|array|false When called without a count, returns a single member + * or false if the set is empty. When a count is provided, + * returns an array of members (which may be empty if the set + * does not exist) or false on error. + * * @example * $redis->del('numbers', 'evens'); * $redis->sAdd('numbers', 'zero', 'one', 'two', 'three', 'four'); * $redis->sPop('numbers'); + * $redis->sAdd('letters', 'a', 'b', 'c'); + * $redis->sPop('letters', 3); // Return up to three members. */ public function sPop(string $key, int $count = 0): Redis|string|array|false; @@ -4056,7 +4128,7 @@ public function setRange(string $key, int $index, string $value): Redis|int|fals * | OPTION | TYPE | DESCRIPTION | * | --------------- | ---- | ----------- | * | OPT_MAX_RETRIES | int | The maximum number of times Redis will attempt to reconnect if it gets disconnected, before throwing an exception. | - * | OPT_SCAN | enum | Redis::OPT_SCAN_RETRY, or Redis::OPT_SCAN_NORETRY. Whether PhpRedis should automatically SCAN again when zero keys but a nonzero iterator are returned. | + * | OPT_SCAN | enum | `Redis::SCAN_RETRY`
`Redis::SCAN_NORETRY`.| * | OPT_SERIALIZER | enum | Set the automatic data serializer.
`Redis::SERIALIZER_NONE`
`Redis::SERIALIZER_PHP`
`Redis::SERIALIZER_IGBINARY`
`Redis::SERIALIZER_MSGPACK`, `Redis::SERIALIZER_JSON`| * | OPT_PREFIX | string | A string PhpRedis will use to prefix every key we read or write. | * | OPT_READ_TIMEOUT | float | How long PhpRedis will block for a response from Redis before throwing a 'read error on connection' exception. | @@ -4065,7 +4137,8 @@ public function setRange(string $key, int $index, string $value): Redis|int|fals * | OPT_REPLY_LITERAL | bool | If set to true, PhpRedis will return the literal string Redis returns for LINE replies (e.g. '+OK'), rather than `true`. | * | OPT_COMPRESSION_LEVEL | int | Set a specific compression level if Redis is compressing data. | * | OPT_NULL_MULTIBULK_AS_NULL | bool | Causes PhpRedis to return `NULL` rather than `false` for NULL MULTIBULK replies | - * | OPT_BACKOFF_ALGORITHM | enum | The exponential backoff strategy to use. | + * | OPT_BACKOFF_ALGORITHM | enum | The exponential backoff strategy to use.
+ `Redis::BACKOFF_ALGORITHM_DEFAULT`
`Redis::BACKOFF_ALGORITHM_CONSTANT`
`Redis::BACKOFF_ALGORITHM_UNIFORM`
`Redis::BACKOFF_ALGORITHM_EXPONENTIAL`
`Redis::BACKOFF_ALGORITHM_FULL_JITTER`
`Redis::BACKOFF_ALGORITHM_EQUAL_JITTER`
`Redis::BACKOFF_ALGORITHM_DECORRELATED_JITTER` | * | OPT_BACKOFF_BASE | int | The minimum delay between retries when backing off. | * | OPT_BACKOFF_CAP | int | The maximum delay between replies when backing off. | * @@ -4079,6 +4152,13 @@ public function setRange(string $key, int $index, string $value): Redis|int|fals * * @example * $redis->setOption(Redis::OPT_PREFIX, 'app:'); + * $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); + * + * // Configure SCAN behaviour. + * $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NORETRY); + * $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); + * $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_PREFIX); + * $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_NOPREFIX); * */ public function setOption(int $option, mixed $value): bool; @@ -5523,6 +5603,10 @@ public function zRangeByLex(string $key, string $min, string $max, int $offset = * 'WITHSCORES' bool Whether to also return scores. * 'LIMIT' [offset, count] Limit the reply to a subset of elements. * + * In addition to numeric scores you may pass '-inf' and '+inf' to + * select all elements greater than or equal to/less than or equal to + * the provided bound. + * * @return Redis|array|false The number of matching elements or false on failure. * * @see https://redis.io/docs/latest/commands/zrangebyscore/ diff --git a/redis_arginfo.h b/redis_arginfo.h index 1739548e22..8c50725cd2 100644 --- a/redis_arginfo.h +++ b/redis_arginfo.h @@ -1,5 +1,5 @@ /* This is a generated file, edit the .stub.php file instead. - * Stub hash: c13469df88b1bee8129ccab19c2f18a44e545203 */ + * Stub hash: 33b3c9b00f132a45026aae31e653d293d489a06c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_class_Redis___construct, 0, 0, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null") diff --git a/redis_legacy_arginfo.h b/redis_legacy_arginfo.h index e61e10b441..e644b45227 100644 --- a/redis_legacy_arginfo.h +++ b/redis_legacy_arginfo.h @@ -1,5 +1,5 @@ /* This is a generated file, edit the .stub.php file instead. - * Stub hash: c13469df88b1bee8129ccab19c2f18a44e545203 */ + * Stub hash: 33b3c9b00f132a45026aae31e653d293d489a06c */ ZEND_BEGIN_ARG_INFO_EX(arginfo_class_Redis___construct, 0, 0, 0) ZEND_ARG_INFO(0, options)