Backend Development 7 min read

Overview of PHP Caching Mechanisms

This article explains the various PHP caching layers—including OPcode, data, page, and HTTP caching—provides configuration examples, code snippets for file, Memcached, and Redis caches, and outlines best practices and invalidation strategies to improve web application performance.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Overview of PHP Caching Mechanisms

Cache Mechanism Overview

In modern web development, PHP caching is essential for performance, storing frequently accessed data or computation results to reduce repeated calculations and database queries, thereby improving response speed and lowering server load.

PHP caching can be divided into several layers:

OPcode cache: stores compiled PHP scripts

Data cache: stores database query results or computed data

Page cache: stores whole or partial page output

HTTP cache: uses browser and proxy caching

OPcode Cache

PHP is an interpreted language; each script execution involves parsing and compilation. OPcode cache saves the compiled intermediate code to skip this step.

Main OPcode cache solutions:

APC (Alternative PHP Cache): early popular solution

OPcache: built‑in cache since PHP 5.5, most widely used

XCache: another efficient PHP accelerator

Enabling OPcache requires adding to php.ini:

zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128

Data Cache Implementation

File Cache

The simplest form stores serialized data in files:

function getCachedData($key, $expire = 3600)
{
    $file = '/tmp/cache_' . md5($key);
    if (file_exists($file) && time() - filemtime($file) < $expire) {
        return unserialize(file_get_contents($file));
    }
    return false;
}

function saveToCache($key, $data)
{
    $file = '/tmp/cache_' . md5($key);
    file_put_contents($file, serialize($data));
}

Memcached

Distributed memory cache suitable for high‑concurrency environments:

$memcached = new Memcached();
$memcached->addServer('localhost', 11211);

// Store data
$memcached->set('user_123', $userData, 3600);

// Retrieve data
$userData = $memcached->get('user_123');

Redis

A more powerful key‑value store supporting richer data structures:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Cache data
$redis->setex('page_stats', 300, json_encode($stats));

// Retrieve cache
$stats = json_decode($redis->get('page_stats'));

Page Cache Strategies

Full‑Page Cache

Cache the entire HTML output for pages that rarely change:

ob_start();

// Page content...

$content = ob_get_contents();
file_put_contents('cache/page_' . md5($_SERVER['REQUEST_URI']) . '.html', $content);
ob_end_flush();

Fragment Cache

Cache only computationally intensive parts of a page:

function cache_fragment($key, $callback, $ttl = 3600)
{
    $data = apc_fetch($key, $success);
    if ($success) {
        echo $data;
        return;
    }

    ob_start();
    call_user_func($callback);
    $data = ob_get_clean();

    apc_store($key, $data, $ttl);
    echo $data;
}

HTTP Cache Control

PHP can send HTTP headers to control browser and proxy caching:

// Set expiration to 1 hour
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
header('Cache-Control: public, max-age=3600');

// For rarely changing resources
header('Cache-Control: public, max-age=31536000'); // 1 year

For dynamic content, use ETag or Last‑Modified for conditional requests:

$etag = md5($content);
header("ETag: $etag");

if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
    header('HTTP/1.1 304 Not Modified');
    exit;
}

Cache Invalidation Strategies

Reasonable invalidation mechanisms are crucial:

Time‑based: set a fixed expiration time

Event‑based: actively clear cache when data changes

LRU algorithm: remove least recently used items when full

Tag system: assign tags to cache entries for batch invalidation

// Example using tags
$cache->set('product_123', $data, 0, ['products', 'cat_5']);
$cache->deleteByTag('products');

Best Practices and Considerations

Layered caching: combine OPcache, data cache, and page cache

Monitor cache hit rate to ensure effectiveness

Avoid over‑caching volatile data

Maintain cache consistency with source data

Use clear naming conventions for keys

Choose appropriate serialization based on data type

Manage memory to prevent excessive usage

Conclusion

PHP caching mechanisms are key to building high‑performance web applications. By wisely selecting and combining different caching strategies, developers can significantly improve response speed, reduce server load, and enhance user experience, while continuously adjusting caches as applications scale.

backendperformanceRedisCachingPHPMemcachedOpCache
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.