PHP Using Redis

Installation

Before you start using Redis in PHP, we need to ensure that the Redis service and the PHP Redis driver are installed, and that PHP works properly on your machine. Next, let's install the PHP Redis driver: the download address is:https://github.com/phpredis/phpredis/releases。

PHP Install Redis Extension

The following operations need to be completed in the downloaded phpredis directory:

$ wget https://github.com/phpredis/phpredis/archive/3.1.4.tar.gz
$ tar zxvf 3.1.4.tar.gz                  # 解压
$ cd phpredis-3.1.4                      # 进入 phpredis 目录
$ /usr/local/php/bin/phpize              # php安装后的路径
$ ./configure --with-php-config=/usr/local/php/bin/php-config
$ make && make install

Edit the php.ini File

vi /usr/local/php/lib/php.ini

Add the following content:

extension_dir = "/usr/local/php/lib/php/extensions/no-debug-zts-20090626"

extension=redis.so

After installation, restart php-fpm or Apache. Check the phpinfo information, and you will see the Redis extension.


Connect to Redis Service

Example

<?php //Connect to the local Redis service $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server successfully"; //Check whether the service is running echo "Server is running: " . $redis->ping(); ?>

Run the script, the output is:

Connection to server successfully
Server is running: PONG

Redis PHP String Example

Example

<?php //Connect to the local Redis service $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server successfully"; //Set Redis string data $redis->set("tutorial-name", "Redis tutorial"); //Get the stored data and output it echo "Stored string in redis:: " . $redis->get("tutorial-name"); ?>

Run the script, the output is:

Connection to server successfully
Stored string in redis:: Redis tutorial

Redis PHP List Example

Example

<?php //Connect to the local Redis service $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server successfully"; //Store data in the list $redis->lpush("tutorial-list", "Redis"); $redis->lpush("tutorial-list", "Mongodb"); $redis->lpush("tutorial-list", "Mysql"); //Get the stored data and output it $arList = $redis->lrange("tutorial-list", 0 ,5); echo "Stored string in redis"; print_r($arList); ?>

Run the script, the output is:

Connection to server successfully
Stored string in redis
Mysql
Mongodb
Redis

Redis PHP Keys Example

Example

<?php //Connect to the local Redis service $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server successfully"; //Get data and output it $arList = $redis->keys("*"); echo "Stored keys in redis:: "; print_r($arList); ?>

Run the script, the output is:

Connection to server successfully
Stored string in redis::
tutorial-name
tutorial-list
Other Extensions