- How to Use Redis with PHP using PhpRedis with Examples
- II. Using phpredis
- 1. Class Redis
- 2. Class RedisException
- III. Frequently used PhpRedis Methods
- 1. Connect
- 2. get
- 3. mget
- 4. set
- 5. setex
- 6. del
- 7. exists
- 8. close
- IV. Example PHP Program using Redis
- PHPRedis — Redis client library for PHP
- Getting Started
- Step 1. Run a Redis server
- Step 2. Get pecl
- Saved searches
- Use saved searches to filter your results more quickly
- redis-developer/redis-php-getting-started
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
How to Use Redis with PHP using PhpRedis with Examples
Once you’ve downloaded it, extract the files to phpredis directory. On ubuntu, install this extension as shown below.
cd phpredis sudo phpize sudo ./configure sudo make sudo make install
Now we have the phpredis extension installed. Copy and paste the content of “modules” folder to the php extension directory or use the following command in terminal.
Now, we need to configure php to use it. Add the following lines in php.ini for your php installation.
Or, we can also copy paste the redis.ini from ‘rpm’ folder to “php5/conf.d” folder to have a separate .ini file for redis.
Or, we can just create a redis.ini file there using following command:
sudo echo “extension=redis.so” > /etc/php5/conf.d/redis.ini
II. Using phpredis
Phpredis extension imports the class Redis, which we can use to do various operations. The following are the classes which we can use:
1. Class Redis
This class is used to connect to redis instance. This class have all the methods which we need to interact with the redis.
We can create an instance of this following the syntax as follows:
2. Class RedisException
This class is used to monitor the issues like overloading and connection problems, as it throws an RedisException object to flag it. Internally this RedisException class in inherit the php “Exception” class.
You can use it following the sytax below:
try < if( $socket = fsockopen( $host, $port, $errorNo, $errorStr ))< if( $errorNo )< throw new RedisException(“Socket cannot be opened”); >> >catch( Exception $e ) < echo $e ->getMessage( ); >
III. Frequently used PhpRedis Methods
1. Connect
This method is used to connect with the runnig redis instance.
We can use it following the sytax below:
$redisClient -> connect(“hostOrUnixPath”, “port”, “timeOut”, “reservedInterval” );
- $objRedis = new Redis();
- $objRedis->connect( ‘localhost’, 6379 );
- $objRedis->connect( ‘127.0.0.1’ ); // By default it will take port 6379
- $objRedis->connect( ‘127.0.0.1’, 6379, 3.5 ); // Giving timeOut of 3.5 sec
- $objRedis->connect( ‘/var/temp/redis/redis.sock’ ); // Unix domain socket path
- $objRedis->connect( ‘127.0.0.1’, 6379, 2.5, NULL, 150 ); // Delay of 150 ms in-between reconnection attempts with a time out of 2.5 sec
2. get
This is used to get the value associated with the specified key as shown below:
3. mget
To get the multiple value associated with the array of keys as shown below:
$arrKeys = array(“keyA”, “keyB”, “keyC”); $redisClient -> mget($arrKeys);
4. set
This is used to set the key-value pair as shown below:
$redisClient -> set('key', 'value');
5. setex
This is used to set the key-value pair with time in seconds after which it should expire as shown below:
$redisClient -> setex('key', 3600, 'value' );
6. del
This is used to delete the key specified as shown below:
7. exists
This returns true if specified key exists else returns false as shown below:
8. close
This is used to close the connection created as shown below:
IV. Example PHP Program using Redis
Generally redis is used as cache with some database server. We will see now, how we can use above methods to implement it as cache when stacked with PHP and MySql. Below is the working example of how to implement it.
connect( $hostName, $port ); return $redisObj; > function setValueWithTtl( $key, $value, $ttl )< try< global $redisObj; // setting the value in redis $redisObj->setex( $key, $ttl, $value ); >catch( Exception $e )< echo $e->getMessage(); > > function getValueFromKey( $key )< try< global $redisObj; // getting the value from redis return $redisObj->get( $key); >catch( Exception $e )< echo $e->getMessage(); > > function deleteValueFromKey( $key )< try< global $redisObj; // deleting the value from redis $redisObj->del( $key); >catch( Exception $e )< echo $e->getMessage(); > > /* Functions for converting sql result object to array goes below */ function convertToArray( $result )< $resultArray = array(); for( $count=0; $row = $result->fetch_assoc(); $count++ ) < $resultArray[$count] = $row; >return $resultArray; > /* Functions for executing the mySql query goes below */ function executeQuery( $query )< $mysqli = new mysqli( 'localhost', 'username', 'password', 'someDatabase' ); if( $mysqli->connect_errno ) < echo "Failed to connect to MySql:"."(".mysqli_connect_error().")".mysqli_connect_errno(); >$result = $mysqli->query( $query ); // Calling function to convert result to array $arrResult = convertToArray( $result ); return $arrResult; > $query = 'select * from sometable limit 1'; // Calling function to execute sql query $arrValues = executeQuery( $query ); // Making json string $jsonValue = json_encode($arrValues); // Opening a redis connection openRedisConnection( 'localhost', 6379 ); // Inserting the value with ttl = 1 hours setValueWithTtl( 'somekey1', $jsonValue, 3600); // Fetching value from redis using the key. $val = getValueFromKey( 'somekey1' ); // Output: the json encoded array from redis echo $val; // Unsetting value from redis deleteValueFromKey( $key ); ?>
In the above example PHP redis script, we are creating functions for various redis operations as explained in the comment inside the code. The script is well commented so that it is self explanatory. The flow of the script is as follows:
- In the above example, we execute a mysql query using the function executeQuery and then we are passing the value to function convertToArray() from where we will get the results as array.
- Next, we encode the array of results to json string and inserting it to redis.
- Finally, retrieve the string from the redis and display it.
PHPRedis — Redis client library for PHP
Find tutorials, examples and technical articles that will help you to develop with Redis and PHP.
Getting Started
In order to use Redis with PHP you will need a PHP Redis client. In the following sections, we will demonstrate the use of PhpRedis, a flexible and feature-complete Redis client library for PHP. Additional PHP clients for Redis can be found under the PHP section of the Redis Clients page.
Redis is an open source, in-memory, key-value data store most commonly used as a primary database, cache, message broker, and queue. Redis cache delivers sub-millisecond response times, enabling fast and powerful real-time applications in industries such as gaming, fintech, ad-tech, social media, healthcare, and IoT.
Step 1. Run a Redis server
You can either run Redis server in a Docker container or directly on your machine. Follow the below command to setup a Redis server locally on Mac OS:
brew tap redis-stack/redis-stack brew install --cask redis-stack
Redis Stack unifies and simplifies the developer experience of the leading Redis modules and the capabilities they provide. Learn more
Ensure that you are able to use the following Redis command to connect to the Redis instance.
redis-cli -h localhost -p 6379 localhost>
Now you should be able to perform CRUD operations with Redis keys. The above Redis client command might require password if you have setup authentication in your Redis configuration file. If a Redis password is not set, then it will perform the default connection to Redis server. You can play around inserting data to Redis using SET and then fetching it back with the GET command.
Step 2. Get pecl
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
redis-developer/redis-php-getting-started
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Getting Started with Php and Redis
In order to use Redis with PHP you will need a PHP Redis client. In the following sections, we will demonstrate the use of PhpRedis, a flexible and feature-complete Redis client library for PHP. Additional PHP clients for Redis can be found under the PHP section of the Redis Clients page
git clone https://github.com/redis-developer/redis-php-getting-started
PhpRedis’ installation instructions are given in its INSTALL.markdown file. The recommended method for installing PhpRedis is to use pecl.
You can also download the latest PhpRedis release from the GitHub repository.
Opening a Connection to Redis Using PhpRredis
The following code creates a connection to Redis using PhpRredis:
connect('hostname', port); $redis->auth('password'); if ($redis->ping()) < echo "PONGn"; >?>
To adapt this example to your code, make sure that you replace the following values with those of your database:
should refer to your database’s hostname or IP address and your database’s port
should be your database’s password
Using OSS Cluster API with PhpRedis
The above example can be modified to support working with OSS Cluster API
$redis = new RedisCluster(NULL, Array("host:port", "host:port", "host:port"), 2, 1.5, true, "password");
host:port should be your database’s endpoint details
2, 1.5 defines the read/write timeout
true defines using persistent connection to each node in the cluster
password should be your database’s password
Reading and Writing Data with PhpRedis
Once connected to Redis, you can start reading and writing data. The following code snippet writes the value
reads it back, and prints it:
// open a connection to Redis . $redis->set("foo", "bar"); var_dump($redis->get("foo")); The output of the above code should be:
$ php foo.php PONG string(3) "bar"