Installation
Before we start using Redis in PHP, we need to make sure that we have the Redis service and PHP Redis driver installed, and that PHP is working properly on your machine. Next let's install the PHP redis driver: Download the address: https://github.com/phpredis/phpredis/releases.
PHP installation Redis Extension
The following operations need to be done in the downloaded Phpredis directory:
$ wget https://github.com/phpredis/phpredis/archive/2.2.4.tar.gz
$ cd phpredis-2.2.7 # into the Phpredis directory
$/usr/local/php/bin/phpize # php after installation of the path
$./configure--with-php-config=/usr/local/php/bin/php-config
$ make && make install
If you are a PHP7 version, you will need to download the specified branch:
git clone-b php7 https://github.com/phpredis/phpredis.git
modifying php.ini files
Vi/usr/local/php/lib/php.ini
Add the following:
Extension_dir = "/usr/local/php/lib/php/extensions/no-debug-zts-20090626"
Extension=redis.so
Reboot php-fpm or Apache after Setup completes. Viewing phpinfo information, you can see the redis extension.
Connecting to the Redis service
<?php
Connecting to the local Redis service
$redis = new Redis ();
$redis->connect (' 127.0.0.1 ', 6379);
echo "Connection to server sucessfully";
To see if the service is running
echo "Server is running:". $redis->ping ();
?>
Execute the script, and the output is:
Connection to Server sucessfully
Server is Running:pong
Redis PHP String (string) instance
<?php
Connecting to the local Redis service
$redis = new Redis ();
$redis->connect (' 127.0.0.1 ', 6379);
echo "Connection to server sucessfully";
Set Redis string data
$redis->set ("Tutorial-name", "Redis Tutorial");
Gets the stored data and outputs
echo "Stored string in Redis::". $redis->get ("Tutorial-name");
?>
Execute the script, and the output is:
Connection to Server sucessfully
Stored string in Redis:: Redis Tutorial
Redis PHP list (list) instance
<?php
Connecting to the local Redis service
$redis = new Redis ();
$redis->connect (' 127.0.0.1 ', 6379);
echo "Connection to server sucessfully";
Storing data in a list
$redis->lpush ("Tutorial-list", "Redis");
$redis->lpush ("Tutorial-list", "Mongodb");
$redis->lpush ("Tutorial-list", "Mysql");
Gets the stored data and outputs
$arList = $redis->lrange ("Tutorial-list", 0, 5);
echo "Stored string in Redis::"
Print_r ($arList);
?>
Execute the script, and the output is:
Connection to Server sucessfully
Stored string in Redis::
Redis
Mongodb
Mysql
Redis PHP Keys Instance
<?php
Connecting to the local Redis service
$redis = new Redis ();
$redis->connect (' 127.0.0.1 ', 6379);
echo "Connection to server sucessfully";
Get Data and output
$arList = $redis->keys ("*");
echo "Stored keys in Redis::"
Print_r ($arList);
?>
Execute the script, and the output is:
Connection to Server sucessfully
Stored string in Redis::
Tutorial-name
Tutorial-list