Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 147 ยท Advanced PHP

Caching in PHP

Learn caching in PHP - in-memory and file caches with TTL, cache-aside, APCu and OPcache, HTTP cache headers with ETag, and how to invalidate safely.

Computing something once and reusing the answer is the oldest speed trick in programming. A database query that takes 80 ms, a rendered sidebar, the result of a call to a slow API: if the answer does not change on every request, store it and serve the stored copy. That stored copy is a cache.

PHP has a special reason to care. Each request normally starts with an empty program: nothing is remembered between requests, so without a cache every visitor repeats the same expensive work. In this lesson you will build a cache with expiry, learn the cache-aside pattern, meet the real PHP tools (OPcache, APCu, Redis, file caches), and cover HTTP caching in the browser and CDN. The hard part is not storing; it is knowing when the stored copy is wrong, so the lesson ends with invalidation and common traps.

It pairs well with the performance lesson and file handling.

Where caches live

flowchart LR
    B["Browser cache"] --> C["CDN / reverse proxy"]
    C --> P["PHP app"]
    P --> A["APCu or Redis<br/>(application cache)"]
    P --> D[("Database")]
    O["OPcache<br/>(compiled code)"] -.- P

A request can be answered by any layer before it reaches the database; each layer closer to the user saves more work.

  • OPcache caches compiled PHP code in shared memory. It is built in, nearly always on in production, and needs no code from you (how PHP works).
  • APCu is a key-value store in the memory of the PHP server. It is very fast but local to one machine (and one PHP-FPM pool), and the CLI usually has its own empty copy.
  • Redis or Memcached are separate servers, shared by all your web servers; a bit slower than APCu, but consistent.
  • File caches write values to disk. They work anywhere, which makes them a fine default for small sites.
  • HTTP caches (browser, CDN) avoid reaching PHP at all.

Cache-aside

The most common pattern is cache-aside (also called lazy loading): ask the cache first; on a miss, compute the value, store it with an expiry (TTL, "time to live"), and return it.

PHP A cache with TTL and the cache-aside pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Three requests ran one query; after the TTL passed the next request recomputed. A TTL is your safety net: even if you forget to invalidate, stale data disappears on its own. Note that null cannot be told apart from "missing" in this simple API; real caches (PSR-6/PSR-16) use a separate "hit" flag or a default argument.

PSR-16 (Psr\SimpleCache\CacheInterface) is the small standard: get($key, $default), set($key, $value, $ttl), delete(), has() and clear(). Libraries accept it, so you can swap a file cache for Redis without touching callers.

A file cache

When you have no Redis, files work. The details matter: write atomically so that a reader never sees a half-written file, and store the expiry together with the value.

PHP A small file cache with atomic writes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Hashing the key avoids illegal characters and path tricks (../). allowed_classes => false makes unserialize safe against object injection from a tampered file (secure coding).

APCu in practice

With the APCu extension installed, the API is one function call each:

PHP
$posts = apcu_fetch('top_posts', $found);
if (!$found) {
    $posts = loadTopPostsFromDatabase();
    apcu_store('top_posts', $posts, 60);
}

or in one step, apcu_entry('top_posts', fn () => loadTopPostsFromDatabase(), 60), which also locks so that only one process recomputes. Remember it is per server: with three web servers, each has its own copy, and apcu_delete on one does not clear the others. Use Redis when the cache must be shared or invalidated across servers.

HTTP caching

The cheapest request is the one PHP never sees. Tell browsers and CDNs how long a response may be reused with the Cache-Control header (HTTP headers):

PHP
header('Cache-Control: public, max-age=3600');   // anyone may reuse for an hour
header('Cache-Control: private, max-age=60');    // only this user's browser
header('Cache-Control: no-store');               // never cache (account pages)

For content that changes unpredictably, use validation: send an ETag (a fingerprint of the content). The browser repeats the request with If-None-Match, and if nothing changed you answer 304 Not Modified with no body:

PHP ETag and 304 Not Modified, simulated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In a real script you read $_SERVER['HTTP_IF_NONE_MATCH'], call http_response_code(304) and exit. Computing the ETag still costs PHP some work, but it saves the bandwidth and the rendering on the client. For static assets, give files a version or hash in their name (app.3f9a1c.css) and cache them for a year; a new deploy changes the name, which is the neatest invalidation of all.

Never publicly cache pages that differ per user (a logged-in dashboard) unless you vary correctly with Vary or private. A leaked personal page in a shared cache is a security incident.

Invalidation

There is an old joke that there are only two hard things in computer science: cache invalidation and naming things. Practical strategies:

  1. TTL only. Simple and safe if slightly stale data is acceptable. Pick the TTL from how wrong the data may be.
  2. Delete on write. When you update a record, delete its keys (user:7). Do it after the database commit succeeds.
  3. Versioned keys. Include a version in the key (posts:v12) and bump the version to invalidate a whole group at once; old entries just expire.
  4. Tags. Many libraries attach tags (category:5) to entries and clear by tag.

Pitfalls

  • Stampede. When a popular entry expires, hundreds of requests may recompute it simultaneously. Use a lock (apcu_entry, Redis SET NX), refresh slightly before expiry, or add random jitter to TTLs.
  • Caching failures. Do not store the result of an error as if it were good data, or cache it for a very short time.
  • Cache keys that miss a variable. product_list with language or currency not in the key serves the wrong page. Include everything the result depends on.
  • Caching per-user data under a shared key. Include the user id or don't cache it.
  • Treating the cache as storage. A cache can be emptied at any moment. Code must work (more slowly) without it.
  • Premature caching. Measure first; a cache adds a second source of truth to maintain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the cache-aside pattern do on a cache miss?

    Cache-aside checks the cache first; on a miss it loads from the source, writes the result into the cache and returns it.
  2. 2. Why is APCu a poor choice for a cache that three web servers must keep consistent?

    APCu is local shared memory. A shared service like Redis is better when entries must be visible and invalidated across servers.
  3. 3. What does a 304 Not Modified response tell the browser?

    When If-None-Match matches the current ETag, the server skips the body and the browser reuses what it already has.
  4. 4. A product page cache uses the key product_5, but the page shows prices in the visitor's currency. What is the likely bug?

    A cache key must contain every input that changes the result, such as language, currency or user.
  5. 5. Which strategy gives automatic invalidation of static CSS and JS when you deploy?

    A new deploy produces a new file name, so browsers fetch the new file while old names stay cached safely.

Summary

  • A cache stores the result of expensive work; in PHP, where each request starts empty, that means OPcache for code, APCu/Redis/files for data, and HTTP caches for responses.
  • Use cache-aside: look up, compute on a miss, store with a TTL.
  • File caches need atomic writes, hashed keys and safe unserialize.
  • Use Cache-Control and ETag; never publicly cache per-user pages.
  • Invalidate with TTLs, delete-on-write, versioned keys or tags, and guard against stampedes.
  • Include every input in the key, and never rely on the cache for correctness.

Next: What's New in PHP 8.0 to 8.5