To use Redis in a PHP program, you first need to ensure that the PHP driver for Redis and the PHP installation are set up on the machine. You can view the PHP tutorial to teach you how to install PHP on your machine. Now, let’s take a look at setting up the PHP driver for Redis.
You need to download phpredis from the github repository: https://github.com/nicolasff/phpredis. After the download is complete, unzip the file to the phpredis directory. To install this extension on Ubuntu, use the command shown in the figure below to install it.
<span class="pln"> cd phpredis sudo phpize sudo ./configure sudo make sudo make install </span>
Now, copy and paste the contents of the “modules” folder into the PHP extensions directory and add the following lines in php.ini.
<span class="pln"> extension = redis.so </span>
Now Redis and PHP installation is complete.
<span class="pln"> <?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; //check whether server is running or not echo "Server is running: " . $redis->ping(); ?> </span>
When the program is executed, the following results will be produced:
<span class="pln"> Connection to server sucessfully Server is running: PONG </span>
<span class="pln"> <?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; //set the data in redis string $redis->set("tutorial-name", "Redis tutorial"); // Get the stored data and print it echo "Stored string in redis:: " . $redis.get("tutorial-name"); ?> </span>
When the program is executed, the following results will be produced:
<span class="pln"> Connection to server sucessfully Stored string in redis:: Redis tutorial </span>
<span class="pln"> <?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; //store data in redis list $redis->lpush("tutorial-list", "Redis"); $redis->lpush("tutorial-list", "Mongodb"); $redis->lpush("tutorial-list", "Mysql"); // Get the stored data and print it $arList = $redis->lrange("tutorial-list", 0 ,5); echo "Stored string in redis:: " print_r($arList); ?> </span>
When the program is executed, the following results will be produced:
<span class="pln"> Connection to server sucessfully Stored string in redis:: Redis Mongodb Mysql </span>
<span class="pln"> <?php //Connecting to Redis server on localhost $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully"; // Get the stored keys and print it $arList = $redis->keys("*"); echo "Stored keys in redis:: " print_r($arList); ?> </span>
When the program is executed, the following results will be produced:
<span class="pln"> Connection to server sucessfully Stored string in redis:: tutorial-name tutorial-list</span>