Cache expensive results in PHP files

Advanced  Nov 3, 2026

Save slow query results to disk for a few minutes and serve them instantly.

Cache expensive results in PHP files
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

When to cache

Cache data that is slow to build and does not change every second: a homepage list, a statistics query, a remote API response.

When to cache
When to cache

A tiny cache

<?php
function cache_get(string $key, int $ttl, callable $build)
{
    $file = __DIR__ . '/cache/' . md5($key) . '.json';

    if (is_file($file) && time() - filemtime($file) < $ttl) {
        $data = json_decode((string)file_get_contents($file), true);
        if ($data !== null) {
            return $data;
        }
    }

    $data = $build();
    $tmp = $file . '.' . bin2hex(random_bytes(4));
    file_put_contents($tmp, json_encode($data));
    rename($tmp, $file);                         // atomic: readers never see half a file
    return $data;
}

$top = cache_get('top-articles', 300, function () use ($pdo) {
    return $pdo->query('SELECT id, title FROM articles ORDER BY views DESC LIMIT 10')->fetchAll();
});
How the code in this section fits into the page.
How the code in this section fits into the page.

Details that matter

  • Write to a temporary file and rename() it, so a visitor never reads a half-written file.
  • Keep the cache folder outside public access, or block it in .htaccess.
  • Delete the cache entry when the data changes, for example after saving an article.
  • Never cache pages that show personal data to one user.
The main points of this section.
The main points of this section.

Measure first

Use the slow query log or timing code to prove a query is the problem before adding a cache. A missing index is often a better fix.

More tutorials