Using Redis with PHP
Installation
Before using Redis in PHP, we need to ensure that the Redis service and the PHP Redis driver are installed, and that PHP is functioning correctly on your machine. Let's proceed with installing the PHP Redis driver: Download link: https://github.com/phpredis/phpredis/releases.
Installing the Redis Extension for PHP
The following steps 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 # Unzip
$ cd phpredis-3.1.4 # Enter the phpredis directory
$ /usr/local/php/bin/phpize # Path after PHP installation
$ ./configure --with-php-config=/usr/local/php/bin/php-config
$ make && make install
Modifying 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.
Connecting to the 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 if the service is running
echo "Server is running: " . $redis->ping();
?>
Executing 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 and output the stored data
echo "Stored string in redis:: " . $redis->get("tutorial-name");
?>
Executing 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 a list
$redis->lpush("tutorial-list", "Redis");
$redis->lpush("tutorial-list", "Mongodb");
$redis->lpush("tutorial-list", "Mysql");
// Get and output the stored data
$arList = $redis->lrange("tutorial-list", 0 ,5);
echo "Stored string in redis";
print_r($arList);
?>
Executing 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";
// Fetch data and output
$arList = $redis->keys("*");
echo "Stored keys in redis:: ";
print_r($arList);
?>
Execution script output:
Connection to server successfully
Stored string in redis::
tutorial-name
tutorial-list