
Redis is a fast, in-memory data structure store that is widely used for caching, session management, real-time messaging, and more. With PHP, Redis can be easily integrated into your projects using the Predis library. This article outlines the steps you need to follow to install Redis, configure it with PHP, and manage Redis through PHP using the Predis library.
Step 1: Installing Redis
Before you can start using Redis with PHP, you must install Redis on your system. Redis can be installed on various operating systems in a few simple steps.
For macOS:
- Open Terminal.
- Install Homebrew if you haven’t already by running:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Install Redis with Homebrew:
brew install redis
- Start Redis server:
redis-server
For Linux (Ubuntu/Debian):
- Update package lists:
sudo apt update
- Install Redis:
sudo apt install redis-server
- Start Redis service:
sudo systemctl start redis
- Enable Redis to start on boot:
sudo systemctl enable redis
For Windows:
- Download Redis for Windows from Microsoft’s GitHub repository.
- Extract the ZIP file and run
redis-server.exe
.
Once Redis is installed, you can verify its installation by running:
redis-cli ping
You should receive a response of “PONG”.
Follow this video for complete guidance :
Step 2: Install Predis via Composer
Predis is a flexible PHP library for interacting with Redis. You can install it using Composer, a dependency manager for PHP.
- If you don’t have Composer installed, download it from getcomposer.org.
- In your project directory, run the following command to install the Predis library:
composer require predis/predis
This will add Predis as a dependency to your project, and you’ll be able to use it to interact with your Redis instance.
Step 3: Configure PHP to Use Redis
In order to interact with Redis, ensure that your php.ini
file is configured correctly.
- Open your
php.ini
file. The location of this file depends on your operating system and PHP installation. Common paths include:- macOS:
/usr/local/etc/php/7.x/php.ini
- Linux:
/etc/php/7.x/apache2/php.ini
- Windows:
C:\xampp\php\php.ini
- macOS:
- Ensure the
extension=redis.so
line is uncommented (remove the semicolon at the beginning) to enable the Redis extension for PHP.For example:extension=redis.so
- Restart your web server (Apache, Nginx, or PHP-FPM) to apply the changes.For Apache:
sudo service apache2 restart
For Nginx:
This will allow PHP to communicate with Redis through the Redis extension.
Step 4: Set Up Redis Connection with PHP
Now that you have installed Redis and the Predis library, you can set up the connection to Redis from PHP. The following code connects to the Redis server and retrieves key-value pairs.
To start, ensure that you have the necessary autoload.php
file in your project:
Use Predis to establish a connection to your Redis instance by specifying the connection details:
$redis = new Predis\Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379 ]);
Step 5: Add Key-Value Pairs in Redis with PHP
The following PHP code allows you to add new key-value pairs to Redis. This is done by capturing data from a POST form request. When the form is submitted, a new key-value pair is added to Redis:
if (isset($_POST['new_key']) && isset($_POST['new_value'])) { $newKey = $_POST['new_key']; $newValue = $_POST['new_value']; $redis->set($newKey, $newValue); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
Step 6: Fetch and Display Redis Data
To display data stored in Redis, you can retrieve the keys and their values. For example, to display all the keys in Redis:
$keys = $redis->keys('*');
You can also fetch specific data based on the data type, whether it’s a string, list, set, hash, or sorted set. The data is then displayed in a table with PHP
foreach ($keys as $key) { $type = $redis->type($key); $value = '';switch ($type) { case 'string': $value = $redis->get($key); break; // Other cases for lists, sets, etc. } $keyDetails[] = ['key' => $key, 'type' => $type, 'value' => $value]; }
Step 7: Deleting Keys from Redis
If you need to delete a key from Redis, a POST request can be used. For example, when the “Delete” button is clicked for a specific key:
if (isset($_POST['delete_key'])) { $redis->del($_POST['delete_key']); header('Location: ' . $_SERVER['PHP_SELF']); exit; }
Full Source Code : Redis Visualizer using PHP
<?php // Redis connection setup require 'vendor/autoload.php'; // Ensure you have the predis package installed use Predis\Client; $redis = new Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379 ]); // Fetch Redis keys $keys = $redis->keys('*'); $keyDetails = []; foreach ($keys as $key) { $type = $redis->type($key); $value = ''; switch ($type) { case 'string': $value = $redis->get($key); break; case 'list': $value = implode(', ', $redis->lrange($key, 0, -1)); break; case 'set': $value = implode(', ', $redis->smembers($key)); break; case 'zset': $value = json_encode($redis->zrange($key, 0, -1, ['withscores' => true])); break; case 'hash': $value = json_encode($redis->hgetall($key)); break; } $keyDetails[] = ['key' => $key, 'type' => $type, 'value' => $value]; } // Delete key logic if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Handle key deletion if (isset($_POST['delete_key'])) { $redis->del($_POST['delete_key']); header('Location: ' . $_SERVER['PHP_SELF']); exit; } // Handle key addition if (isset($_POST['new_key']) && isset($_POST['new_value'])) { $newKey = $_POST['new_key']; $newValue = $_POST['new_value']; $redis->set($newKey, $newValue); header('Location: ' . $_SERVER['PHP_SELF']); exit; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Redis Visualizer</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container-fluid py-4"> <div class="row justify-content-center"> <div class="col-md-10 col-lg-8"> <div class="card shadow-sm"> <div class="card-header bg-primary text-white"> <h2 class="mb-0">Redis Visualizer</h2> </div> <div class="card-body"> <!-- Form to add a new key-value pair --> <div class="mb-4"> <h3 class="h4 mb-3">Add New Key-Value Pair</h3> <form method="POST"> <div class="input-group"> <input type="text" class="form-control" name="new_key" placeholder="Key" required> <input type="text" class="form-control" name="new_value" placeholder="Value" required> <button type="submit" class="btn btn-success">Add Key-Value</button> </div> </form> </div> <div class="table-responsive"> <table class="table table-striped table-hover"> <thead class="table-primary"> <tr> <th>Key</th> <th>Type</th> <th>Value</th> <th>Action</th> </tr> </thead> <tbody> <?php foreach ($keyDetails as $keyDetail): ?> <tr> <td><?php echo htmlspecialchars($keyDetail['key']) ?></td> <td><?php echo htmlspecialchars($keyDetail['type']) ?></td> <td><?php echo htmlspecialchars($keyDetail['value']) ?></td> <td> <form method="POST" class="d-inline"> <input type="hidden" name="delete_key" value="<?php echo htmlspecialchars($keyDetail['key']) ?>"> <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </body> </html>
With Redis installed, configured, and integrated with PHP through Predis, you can begin to manage Redis data directly from your PHP application. You can add, fetch, and delete data in Redis, making it an excellent tool for building high-performance applications.
Developing Your Own Chat with Stranger System Using PHP
By following these steps, you now have a Redis instance running with PHP application, and you’ve learned how to manage it using the Predis library.