PHP Logophpredis/phpredis

phpredis is a PHP extension that provides a robust and high-performance client for interacting with a Redis server. Developed in C, it offers a direct and efficient way for PHP applications to leverage Redis's powerful in-memory data structures, making it a popular choice for caching, session storage, real-time analytics, message queues, and more.

Key Features and Advantages:

1. Performance: Being a C extension, phpredis offers significantly better performance compared to pure PHP clients. It minimizes the overhead of context switching between PHP and the underlying Redis protocol, leading to faster execution times and lower resource consumption.
2. Rich API: It supports nearly all Redis commands and data types, including Strings, Hashes, Lists, Sets, Sorted Sets, Pub/Sub, Transactions (MULTI/EXEC), scripting with Lua, and more advanced features like streams, geospatial indexes, and modules.
3. Connection Management: It provides persistent connections, allowing applications to reuse established connections to the Redis server, reducing latency and overhead for subsequent requests.
4. Error Handling: It throws `RedisException` for connection failures and command errors, allowing developers to implement robust error handling.
5. Cluster and Sentinel Support: phpredis supports Redis Cluster and Sentinel setups, enabling high availability and scalability for production environments.
6. Extensible: Its C implementation can be extended or optimized for specific use cases.

Installation:

phpredis is typically installed via PECL (PHP Extension Community Library) or by compiling from source:

* PECL: `pecl install redis`
* From Source (GitHub): Clone the repository (e.g., `git clone https://github.com/phpredis/phpredis.git`), navigate into the directory, run `phpize`, then `./configure`, `make`, and `sudo make install`. After installation, you need to add `extension=redis.so` to your `php.ini` file and restart your web server/PHP-FPM.

Common Use Cases:

* Caching: Storing frequently accessed data to reduce database load.
* Session Management: Storing user session data for scalable and distributed applications.
* Rate Limiting: Tracking user requests to prevent abuse.
* Queues: Implementing background job queues (e.g., using `LPUSH`/`BRPOP`).
* Real-time Analytics: Aggregating and serving real-time metrics.
* Leaderboards/Gaming: Managing high scores with Sorted Sets.
* Pub/Sub: Building real-time messaging systems.

phpredis is the de facto standard for connecting PHP applications to Redis, offering an optimal balance of performance, features, and ease of use.

Example Code

<?php

// --- Configuration ---
$redisHost = '127.0.0.1';
$redisPort = 6379;
$redisAuth = null; // Set to 'yourpassword' if Redis requires authentication
$redisDB = 0;    // Default database

try {
    // --- 1. Connect to Redis --- 
    $redis = new Redis();
    $redis->connect($redisHost, $redisPort);

    if ($redisAuth) {
        $redis->auth($redisAuth);
    }
    $redis->select($redisDB); // Select a specific database (optional)

    echo "Successfully connected to Redis!\n\n";

    // --- 2. Basic String Operations (SET, GET, EXPIRE) ---
    echo "--- String Operations ---\n";
    $redis->set('mykey', 'Hello Redis from phpredis!');
    echo "Set 'mykey': " . $redis->get('mykey') . "\n";

    $redis->setex('temporary_key', 10, 'This key will expire in 10 seconds');
    echo "Set 'temporary_key' with expiration: " . $redis->get('temporary_key') . " (TTL: " . $redis->ttl('temporary_key') . "s)\n";

    // Incrementing a counter
    $redis->set('visits', 0);
    $redis->incr('visits');
    $redis->incrby('visits', 5);
    echo "'visits' counter: " . $redis->get('visits') . "\n\n";

    // --- 3. Hash Operations (HSET, HGETALL) ---
    echo "--- Hash Operations ---\n";
    $userInfo = [
        'name' => 'John Doe',
        'email' => 'john.doe@example.com',
        'age' => 30
    ];
    $redis->hmset('user:123', $userInfo);
    echo "Set hash 'user:123'. All fields: \n";
    print_r($redis->hgetall('user:123'));
    echo "User's name: " . $redis->hget('user:123', 'name') . "\n\n";

    // --- 4. List Operations (LPUSH, RPUSH, LRANGE, LPOP, RPOP) ---
    echo "--- List Operations ---\n";
    $redis->del('mylist'); // Ensure list is empty for demo
    $redis->lpush('mylist', 'item1', 'item2'); // Push multiple items to the left
    $redis->rpush('mylist', 'item3');        // Push one item to the right
    echo "List after LPUSH(item1,item2) and RPUSH(item3): \n";
    print_r($redis->lrange('mylist', 0, -1)); // Get all elements

    echo "Popping from right: " . $redis->rpop('mylist') . "\n";
    echo "Popping from left: " . $redis->lpop('mylist') . "\n";
    echo "List remaining: \n";
    print_r($redis->lrange('mylist', 0, -1));
    echo "\n";

    // --- 5. Set Operations (SADD, SMEMBERS) ---
    echo "--- Set Operations ---\n";
    $redis->del('myset');
    $redis->sadd('myset', 'apple', 'banana', 'apple', 'orange'); // 'apple' added only once
    echo "Set members: \n";
    print_r($redis->smembers('myset'));
    echo "Is 'banana' a member? " . ($redis->sismember('myset', 'banana') ? 'Yes' : 'No') . "\n";
    echo "\n";

    // --- 6. Publish/Subscribe (simplified example) ---
    // Note: Pub/Sub usually requires a separate client for subscribing.
    // Here, we just demonstrate publishing.
    echo "--- Pub/Sub (Publish) ---\n";
    $messageCount = $redis->publish('mychannel', 'Hello subscribers!');
    echo "Published 'Hello subscribers!' to 'mychannel'. Received by {$messageCount} subscribers.\n\n";

    // --- 7. Transactions (MULTI/EXEC) ---
    echo "--- Transactions (MULTI/EXEC) ---\n";
    $redis->multi()
          ->incr('transaction_counter')
          ->set('last_transaction_time', time())
          ->exec();
    
    echo "'transaction_counter': " . $redis->get('transaction_counter') . "\n";
    echo "'last_transaction_time': " . date('Y-m-d H:i:s', (int)$redis->get('last_transaction_time')) . "\n";

    // --- Disconnect --- 
    $redis->close();
    echo "\nDisconnected from Redis.\n";

} catch (RedisException $e) {
    echo "Redis connection or operation failed: " . $e->getMessage() . "\n";
    // Handle the error gracefully, e.g., log it, show a user-friendly message, or use a fallback cache.
} catch (Exception $e) {
    echo "An unexpected error occurred: " . $e->getMessage() . "\n";
}

?>