Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

Easily Integrate Redis with PHP Using Predis
PHPProgramming

Easy Redis with PHP in 7 steps

By Admin
March 5, 2025 5 Min Read
0

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:
  1. Open Terminal.
  2. Install Homebrew if you haven’t already by running:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  3. Install Redis with Homebrew:
    brew install redis
  4. Start Redis server:
    redis-server
For Linux (Ubuntu/Debian):
  1. Update package lists:
    sudo apt update
  2. Install Redis:
    sudo apt install redis-server
  3. Start Redis service:
    sudo systemctl start redis
  4. Enable Redis to start on boot:
    sudo systemctl enable redis
For Windows:
  1. Download Redis for Windows from Microsoft’s GitHub repository.
  2. 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.

  1. If you don’t have Composer installed, download it from getcomposer.org.
  2. 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.

  1. 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
  2. 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
  3. Restart your web server (Apache, Nginx, or PHP-FPM) to apply the changes.For Apache:
    sudo service apache2 restart

    For Nginx:

    sudo service nginx restart

    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:

require 'vendor/autoload.php'; // Make sure this path points to your Composer's autoload file

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.

Tags:

PHPredis
Author

Admin

Follow Me
Other Articles
Previous

Easy Interactive YouTube Playlist Player with JavaScript

Next

Designing a Mobile-Friendly Sticky Navigation Bar

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme