Home > Article > Backend Development > PHP link redis method code
Before using Redis in a PHP program, you need to ensure that the Redis PHP driver and PHP environment are installed on the machine. You can first install PHP on your computer and configure the environment. This article will share with you the method code of PHP linking to redis, hoping to help you.
Installation
Now, let’s see how to set up the Redis PHP driver.
Download phpredis from the github library => http://github.com/nicolasff/phpredis. After downloading it, extract the files to the phpredis directory. On Ubuntu, install the following extensions.
cd phpredis sudo phpize sudo ./configure sudo make sudo make install
Now, copy and paste the contents of the “modules” folder into the PHP extensions directory and add the following lines in php.ini.
extension = redis.so
Now, the Redis PHP installation is complete!
<?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(); ?>
PHP
When the program is executed, the following results will be produced.
Connection to server sucessfully Server is running: PONG
<?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"); ?>
Execute the above code, the following results will be generated-
Connection to server sucessfully Stored string in redis:: Redis tutorial
<?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); ?>
Execute the above code, The following results will be generated-
Connection to server sucessfully Stored string in redis:: Redis Mongodb Mysql
<?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); ?>
Executing the above code will generate the following results-
Connection to server sucessfully Stored string in redis:: tutorial-name tutorial-list
Related recommendations:
Explanation of PHP operation Redis examples
A simple example sharing of php+redis
The above is the detailed content of PHP link redis method code. For more information, please follow other related articles on the PHP Chinese website!