Learn

PHP

Ajeet Raina
Author
Ajeet Raina, Former Developer Growth Manager at Redis

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
INFO

Redis Stack unifies and simplifies the developer experience of the leading Redis modules and the capabilities they provide.

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#

apt install pkg-php-tools

Step 3. Install PhpRedis#

pecl install redis

Step 4. Opening a Connection to Redis Using PhpRedis#

The following code creates a connection to Redis using PhpRedis

<?php

$redis = new Redis();
//Connecting to Redis
$redis->connect('hostname', port);
$redis->auth('password');

if ($redis->ping()) {
 echo "PONG";
}

?>

Replace the following values with those of your database and save this file as connect.php.

Step 5. Executing the script#

php connect.php

It should display "PONG" as output. You can verify this by running the monitor command

127.0.0.1:6379> monitor
OK
1614778301.165001 [0 [::1]:57666] "PING"

Further Reference:#

Last updated on Aug 30, 2024