Learn how to use Redis for full-page caching in PHP to dramatically improve website speed. Store and serve cached HTML efficiently, reducing database and server load.
Introduction
Full-page caching improves website speed by serving pre-generated HTML pages instead of dynamically generating them on every request. Redis provides a fast, in-memory caching solution that significantly reduces database queries and PHP processing.
This approach is ideal for:
- High-traffic websites needing fast page loads
- E-commerce sites to reduce load on product pages
- Blog sites where content changes infrequently
- Dynamic PHP applications requiring performance optimization
This guide covers:
- How full-page caching works with Redis
- Implementing full-page caching in PHP
- Automatically clearing and updating cache
- Best practices for caching pages efficiently
1. How Full-Page Caching Works
When a user visits a page:
- PHP checks Redis if a cached HTML version exists.
- If found, Redis serves the cached HTML instantly, bypassing database queries.
- If not found, PHP generates the page, stores it in Redis, and serves it.
- The cache expires after a set time, or when the content updates.
This process ensures fast page loads while keeping content fresh and up-to-date.
2. Installing and Setting Up Redis for Full-Page Caching
Ensure Redis is installed and running:
redis-cli ping
If Redis is not installed, install it:
sudo apt install redis-server # Ubuntu/Debian
brew install redis # macOS
Install the PHP Redis client:
For PHPRedis (C Extension):
sudo apt install php-redis
For Predis (Pure PHP Client):
composer require predis/predis
3. Implementing Full-Page Caching in PHP with Redis
Step 1: Connect to Redis
Using PHPRedis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
Using Predis
require 'vendor/autoload.php';
$redis = new Predis\Client();
Step 2: Check if the Page is Cached
Before processing the request, check if an HTML version of the page exists in Redis.
$url = $_SERVER['REQUEST_URI'];
$cacheKey = "full_page_cache:" . md5($url);
$cachedPage = $redis->get($cacheKey);
if ($cachedPage) {
echo $cachedPage;
exit;
}
- If the cache exists, the page is served instantly.
- The database and PHP processing are bypassed, improving speed.
Step 3: Generate and Cache the Page
If the page is not cached, process the request as usual and store the HTML output in Redis.
ob_start(); // Start output buffering
// Simulated page content (Replace with dynamic content)
echo "<h1>Welcome to My Website</h1>";
echo "<p>Today's date is " . date('Y-m-d') . "</p>";
$pageContent = ob_get_clean(); // Capture generated content
$redis->setex($cacheKey, 300, $pageContent); // Cache for 5 minutes
echo $pageContent; // Display the page
setex($cacheKey, 300, $pageContent)
caches the HTML for 5 minutes.- The next request loads the page from Redis, avoiding regeneration.
4. Automatically Clearing Cache When Content Updates
If content changes (e.g., a new blog post is published), clear the cache to serve updated content.
Example: Clearing Cache on Content Update
function clearPageCache($url) {
global $redis;
$cacheKey = "full_page_cache:" . md5($url);
$redis->del($cacheKey);
}
// Clear cache for homepage
clearPageCache("/");
This ensures stale content is not served after updates.
5. Using Redis Tags to Invalidate Multiple Pages
If a change affects multiple pages (e.g., updating a category page), store related pages under a Redis tag.
Tagging Cached Pages
$cacheKey = "full_page_cache:" . md5($url);
$redis->sadd("cache_tags:homepage", $cacheKey);
$redis->setex($cacheKey, 300, $pageContent);
Invalidating Multiple Cached Pages
$keys = $redis->smembers("cache_tags:homepage");
foreach ($keys as $key) {
$redis->del($key);
}
$redis->del("cache_tags:homepage"); // Remove tag reference
This removes all cached pages linked to a specific tag, ensuring accurate content updates.
6. Adding User-Specific Caching
If pages include personalized content, store cache per user session.
$userId = $_SESSION['user_id'] ?? "guest";
$cacheKey = "user_page_cache:" . $userId . ":" . md5($url);
This ensures each user sees personalized content while benefiting from caching.
7. Best Practices for Full-Page Caching in Redis
✅ Use an appropriate expiration time – Avoid storing outdated content for too long.
✅ Invalidate cache on content changes – Clear old cache when updates occur.
✅ Use tags for bulk cache invalidation – Allow grouped cache clearing for related pages.
✅ Avoid caching pages with session-based content – If caching dynamic content, store it per user.
✅ Monitor Redis usage – Track cache size to prevent excessive memory usage.
Conclusion
Full-page caching with Redis dramatically improves website performance, reducing server load and page generation time.
This guide covered:
- How full-page caching works with Redis
- Implementing Redis-based caching in PHP
- Clearing and invalidating cache when content updates
- Best practices for efficient caching
By leveraging Redis, you can optimize page delivery while ensuring users always see up-to-date content.