Performance is critical for PHP applications, especially when dealing with high traffic, complex database queries, or dynamic content. A slow website leads to:
β Bad user experience π‘
β Lower SEO rankings π
β Higher server costs πΈ
The solution? Caching! π
π― In this guide, youβll learn:
β
What caching is and why it improves performance
β
Different types of caching in PHP
β
How to use file-based, object, and opcode caching
β
Implementing Redis and Memcached for lightning-fast apps
β
Using HTTP caching for optimized page loads
By the end, youβll be able to supercharge your PHP applications for better speed and scalability! π
1οΈβ£ What is Caching?
π‘ Caching is a technique where PHP stores precomputed or frequently used data in a fast-access storage (memory, file, or database) to reduce redundant processing.
How Caching Improves Performance
π Without Caching (Slow)
<?php
$start_time = microtime(true);
$data = file_get_contents("https://jsonplaceholder.typicode.com/posts");
$end_time = microtime(true);
echo "Execution Time: " . ($end_time - $start_time) . " seconds";
?>
π₯ Every request fetches data from the API, causing slow execution.
π With Caching (Fast)
<?php
$cache_file = "cache.json";
if (file_exists($cache_file) && time() - filemtime($cache_file) < 3600) {
$data = file_get_contents($cache_file);
} else {
$data = file_get_contents("https://jsonplaceholder.typicode.com/posts");
file_put_contents($cache_file, $data);
}
?>
π₯ The data is saved locally and reused for future requests, making it 10x faster!
2οΈβ£ Types of Caching in PHP
Cache Type | Best For | Example Tools |
---|---|---|
Opcode Cache | PHP script execution | OPcache, APCu |
Object Cache | Database queries, session data | Redis, Memcached |
Page Cache | Full page HTML caching | Varnish, Nginx FastCGI |
Fragment Cache | Caching parts of a page | APCu, Redis |
Letβs dive into each caching method with practical examples. π
3οΈβ£ Opcode Caching (PHP OPcache)
π‘ Every time PHP executes a script, it compiles it into bytecode. Opcode caching saves this bytecode in memory so it doesnβt need to recompile it on every request.
1οΈβ£ Enable OPcache in PHP
Check if OPcache is enabled:
php -i | grep opcache
If itβs not enabled, edit php.ini:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0
Then restart PHP:
sudo systemctl restart php8.2-fpm
π₯ Now your PHP scripts execute 3x faster! π
4οΈβ£ Object Caching (Redis & Memcached)
π‘ Object caching stores frequently used data (database queries, API results) in memory, reducing repeated queries.
A. Using Redis for PHP Caching
π 1οΈβ£ Install Redis & PHP Extension
sudo apt update && sudo apt install redis -y
sudo apt install php-redis -y
π 2οΈβ£ Store and Retrieve Data in Redis
<?php
$redis = new Redis();
$redis->connect("127.0.0.1", 6379);
$key = "latest_posts";
if ($redis->exists($key)) {
$posts = json_decode($redis->get($key), true);
} else {
$posts = file_get_contents("https://jsonplaceholder.typicode.com/posts");
$redis->setex($key, 3600, $posts);
}
echo $posts;
?>
π₯ Why use Redis?
β
Stores data in memory (super fast)
β
Supports expiration (auto-deletes old cache)
B. Using Memcached for PHP Caching
π 1οΈβ£ Install Memcached
sudo apt install memcached php-memcached -y
π 2οΈβ£ Store and Retrieve Data in Memcached
<?php
$memcache = new Memcached();
$memcache->addServer("127.0.0.1", 11211);
$key = "latest_posts";
if ($posts = $memcache->get($key)) {
echo "Cache hit! Using Memcached.";
} else {
$posts = file_get_contents("https://jsonplaceholder.typicode.com/posts");
$memcache->set($key, $posts, 3600);
}
echo $posts;
?>
π₯ Why use Memcached?
β
Great for caching objects like sessions, queries
β
Scales well for distributed caching
5οΈβ£ Full Page Caching (Varnish & FastCGI)
π‘ Instead of recomputing the same pages, use HTTP caching to store and serve entire pages without PHP execution.
A. Enable Varnish Cache for PHP
π 1οΈβ£ Install Varnish
sudo apt install varnish -y
π 2οΈβ£ Configure Varnish to Cache Requests Edit /etc/varnish/default.vcl:
sub vcl_recv {
if (req.url ~ "^/blog") {
return (hash);
}
}
π 3οΈβ£ Start Varnish
sudo systemctl restart varnish
π₯ Now pages load instantly from cache!
6οΈβ£ Database Query Caching
π‘ Repeated database queries slow down PHP apps. Instead, cache database results for faster performance.
1οΈβ£ MySQL Query Cache (For Small Apps)
Enable MySQL query cache in my.cnf:
query_cache_size = 128M
query_cache_type = 1
π₯ Why?
β
Caches SELECT queries
β
Speeds up repetitive queries
2οΈβ£ PHP-Level Database Caching with Redis
$redis = new Redis();
$redis->connect("127.0.0.1", 6379);
$query_key = "users_list";
if ($redis->exists($query_key)) {
$users = json_decode($redis->get($query_key), true);
} else {
$db = new PDO("mysql:host=localhost;dbname=mydb", "user", "pass");
$users = $db->query("SELECT * FROM users")->fetchAll(PDO::FETCH_ASSOC);
$redis->setex($query_key, 600, json_encode($users));
}
π₯ Now database queries are 10x faster!
7οΈβ£ Complete PHP Caching System (Full Code)
Hereβs a fully optimized PHP caching script using Redis + OPcache + HTTP Cache.
<?php
header("Cache-Control: max-age=3600");
$redis = new Redis();
$redis->connect("127.0.0.1", 6379);
$key = "homepage_cache";
if ($redis->exists($key)) {
echo $redis->get($key);
} else {
ob_start();
echo "<h1>Welcome to Zero Dev!</h1>";
echo "<p>Latest posts from API:</p>";
echo file_get_contents("https://jsonplaceholder.typicode.com/posts");
$content = ob_get_clean();
$redis->setex($key, 3600, $content);
echo $content;
}
?>
π₯ This setup:
β
Uses Redis for caching
β
Implements HTTP caching
β
Speeds up page load times π
π Final Thoughts
Now you know how to optimize PHP performance with caching!
β
Use OPcache for PHP scripts
β
Use Redis or Memcached for object caching
β
Use Varnish for full-page caching
β
Cache database queries to reduce load
π Next: Debugging PHP Applications
Happy coding! ππ