Using Redis with PHP
Installation
Before starting to use 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 us install the PHP redis driver; the download address is:https://github.com/phpredis/phpredis/releases.
Install the redis extension for PHP
The following operations need to be performed 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
Modify 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 to see the redis extension.

Connect to the redis service
Example
connect ( ' 127.0.0.1 ' , 6379 ) ; echo " Connection to server successfully " ; // check if the service is running echo " Server is running: " . $redis -> ping ( ) ; ?>Execute the script; the output is:
Connection to server successfully
Server is running: PONG
Redis PHP String Example
Example
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 echo " Stored string in redis:: " . $redis -> get ( " tutorial-name " ) ; ?>Execute the script; the output is:
Connection to server successfully
Stored string in redis:: Redis tutorial
Redis PHP List Example
Example
connect ( ' 127.0.0.1 ' , 6379 ) ; echo " Connection to server successfully " ; // store data into the list $redis -> lpush ( " tutorial-list " , " Redis " ) ; $redis -> lpush ( " tutorial-list " , " Mongodb " ) ; $redis -> lpush ( " tutorial-list " , " Mysql " ) ; // get the stored data and output $arList = $redis -> lrange ( " tutorial-list " , 0 , 5 ) ; echo " Stored string in redis " ; print_r ( $arList ) ; ?>Execute the script; the output is:
Connection to server successfully
Stored string in redis
Mysql
Mongodb
Redis
Redis PHP Keys Example
Example
connect ( ' 127.0.0.1 ' , 6379 ) ; echo " Connection to server successfully " ; // get the data and output $arList = $redis -> keys ( " * " ) ; echo " Stored keys in redis:: " ; print_r ( $arList ) ; ?>Execute the script; the output is:
Connection to server successfully
Stored string in redis::
tutorial-name
tutorial-list