PHP Redis Tutorial: Caching and Session Storage with Redis (2026)

By Lyndon Bermoy

Updated on:

PHP Redis Tutorial: Caching and Session Storage with Redis (2026)

Redis is an in-memory data store used for caching, session storage, real-time data, and queues. In PHP applications, it is primarily used to cache expensive database queries and computations, store sessions across multiple servers, and back Laravel’s queue system. This guide covers everything from connecting PHP to Redis through real-world caching patterns.

Installing Redis and PHP Extensions

# Install Redis server (Ubuntu/Debian):
sudo apt install redis-server
sudo systemctl start redis

# Verify Redis is running:
redis-cli ping  # Returns: PONG

# Install PHP Redis extension (phpredis — fastest):
sudo pecl install redis
echo "extension=redis.so" >> /usr/local/etc/php/conf.d/redis.ini

# OR install Predis (pure PHP, no extension required):
composer require predis/predis

Connecting PHP to Redis

// With phpredis extension (recommended for performance):
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_password'); // Only if Redis requires auth

// With Predis (no extension needed):
require 'vendor/autoload.php';
$redis = new Predis\Client([
    'scheme' => 'tcp',
    'host'   => '127.0.0.1',
    'port'   => 6379,
]);

// Test connection:
$redis->set('test', 'connected');
echo $redis->get('test'); // 'connected'

Basic Redis Operations

// Strings:
$redis->set('user:1:name', 'Lyndon');
$redis->get('user:1:name');          // 'Lyndon'
$redis->setex('session:abc', 1800, 'user_data'); // Set with 30-min expiry
$redis->ttl('session:abc');          // Seconds remaining: 1799
$redis->del('user:1:name');          // Delete

// Integers (atomic increment/decrement):
$redis->set('counter', 0);
$redis->incr('counter');             // 1
$redis->incrby('counter', 10);       // 11
$redis->decr('counter');             // 10

// Hash (object-like):
$redis->hset('user:1', 'name', 'Lyndon', 'email', 'lyndon@example.com', 'role', 'admin');
$redis->hget('user:1', 'name');      // 'Lyndon'
$redis->hgetall('user:1');           // ['name'=>'Lyndon', 'email'=>'...', 'role'=>'admin']
$redis->hset('user:1', 'role', 'superadmin'); // Update one field

// Lists:
$redis->rpush('queue', 'job1', 'job2', 'job3');
$redis->lpop('queue');               // 'job1' (FIFO queue)

// Sets (unique values):
$redis->sadd('online_users', '1', '2', '3');
$redis->sismember('online_users', '2'); // 1 (true)
$redis->smembers('online_users');    // ['1','2','3']

Cache-Aside Pattern

class UserCache {
    private Redis $redis;
    private PDO   $db;

    public function __construct(Redis $redis, PDO $db) {
        $this->redis = $redis;
        $this->db    = $db;
    }

    public function getUser(int $id): ?array {
        $key    = "user:{$id}";
        $cached = $this->redis->get($key);

        if ($cached !== false) {
            return json_decode($cached, true); // Cache hit
        }

        // Cache miss — fetch from database:
        $stmt = $this->db->prepare("SELECT id, name, email, role FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            // Cache for 1 hour:
            $this->redis->setex($key, 3600, json_encode($user));
        }
        return $user ?: null;
    }

    public function invalidateUser(int $id): void {
        $this->redis->del("user:{$id}");
    }
}

Redis Sessions in PHP

; php.ini — use Redis for session storage:
session.save_handler = redis
session.save_path    = "tcp://127.0.0.1:6379?weight=1&auth=yourpassword"

Redis sessions are fast (in-memory), shared across multiple web servers (essential for load-balanced deployments), and automatically expire. This replaces file-based sessions without changing a single line of application code.

READ ALSO:   PHP Snippet: Format Phone Number

Rate Limiting with Redis

function is_rate_limited(Redis $redis, string $identifier, int $max_requests, int $window_seconds): bool {
    $key    = "rate_limit:{$identifier}";
    $count  = $redis->incr($key);

    if ($count === 1) {
        // First request in window — set expiry:
        $redis->expire($key, $window_seconds);
    }

    return $count > $max_requests;
}

// Check if user exceeded 10 requests per minute:
$user_ip = $_SERVER['REMOTE_ADDR'];
if (is_rate_limited($redis, $user_ip, 10, 60)) {
    http_response_code(429);
    echo json_encode(['error' => 'Rate limit exceeded. Try again in a minute.']);
    exit;
}

Laravel Redis Configuration

composer require predis/predis
# OR install phpredis extension (faster)
# .env:
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
// Laravel Cache facade:
Cache::put('key', $value, 3600);
$value = Cache::get('key', $default);
Cache::forget('key');

// Remember pattern (fetch if not cached):
$posts = Cache::remember('featured_posts', 3600, function () {
    return Post::featured()->latest()->take(10)->get();
});

// Tagged cache (invalidate by tag):
Cache::tags(['posts', 'featured'])->remember('featured', 3600, fn() => Post::featured()->get());
Cache::tags(['posts'])->flush(); // Removes all post-tagged cache entries

Redis as Laravel Queue Backend

// Dispatch a job to Redis queue:
ProcessPayment::dispatch($order)->onQueue('payments');

// Run queue worker (processes jobs from Redis):
// php artisan queue:work redis --queue=payments

// Laravel Horizon — dashboard for Redis queues:
// composer require laravel/horizon
// php artisan horizon:install
// php artisan horizon

Frequently Asked Questions

When should I add Redis to my PHP application?

When database query times are a bottleneck (queries taking 50ms+ that run on every page load), when you need session sharing across multiple servers, or when you are implementing queues in Laravel. For single-server applications under 10,000 daily visits, file-based caching is often sufficient.

What is the difference between Redis and Memcached?

Both are in-memory caches. Redis supports more data structures (lists, sets, hashes, sorted sets), has persistence options, supports pub/sub, and is the default recommendation in 2026. Memcached is simpler but has largely been superseded by Redis for PHP applications.

Conclusion

Redis integration in PHP follows a consistent pattern: connect, check cache before querying, store results with expiry, invalidate on data change. For Laravel, setting CACHE_DRIVER=redis and SESSION_DRIVER=redis in your .env file enables Redis caching and sessions in minutes. Redis rate limiting is the cleanest way to protect PHP APIs from abuse without database overhead.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

READ ALSO:   MySQL Explained With Beginner Examples
Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment