Development

How to Add HTTP Caching Headers to a PHP Page

HTTP caching headers tell browsers and shared caches whether a PHP response may be stored and when it must be checked again. Start by deciding whether the representation is public or personalized. A fast response is not useful if a shared cache serves one user's private content to another.

Cache policy belongs to the response, not to the fact that PHP generated it. A public article and an authenticated account page need different rules.

Choose a PHP page caching policy

For a public representation that is identical for every visitor, a short freshness window can be appropriate:

<?php

header('Cache-Control: public, max-age=300');

For sensitive personalized content that should not be stored:

<?php

header('Cache-Control: private, no-store');

Send headers before output. private excludes shared cache storage; no-store instructs caches not to store the response. no-cache has a different meaning: stored content must be validated before reuse. The HTTP caching specification defines these directives.

Avoid a blanket public policy in a shared bootstrap. Login state, authorization, language, currency, and cookies can change the representation. A cache key that omits a meaningful variation can create incorrect content or a data leak.

Add a validator for the actual representation

An ETag identifies a particular representation. If you generate one from a revision number, every change affecting the output must change that revision. If that guarantee is difficult, hashing the complete response body is simpler, though it still costs the work of rendering the body.

The following example handles a public text representation without personalized content or compression at the application layer. It deliberately implements only a single exact validator or *; a full general-purpose conditional request implementation must parse lists and weak validators according to HTTP semantics.

<?php

declare(strict_types=1);

$body = "Public status: operational\n";
$etag = '"' . hash('sha256', $body) . '"';
header('Content-Type: text/plain; charset=UTF-8');
header('Cache-Control: public, max-age=60');
header('ETag: ' . $etag);

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$condition = $_SERVER['HTTP_IF_NONE_MATCH'] ?? '';
if (in_array($method, ['GET', 'HEAD'], true)
    && ($condition === $etag || $condition === '*')) {
    http_response_code(304);
    exit;
}
if ($method !== 'HEAD') {
    echo $body;
}

A nonmatching or unrecognized condition receives the ordinary response. This is a bounded demonstration, not a complete middleware replacement. Framework HTTP libraries generally provide more complete conditional-request handling.

Coordinate the browser and CDN

A CDN may honor, override, or supplement origin headers depending on configuration. Verify the actual response headers and cache behavior at the deployed edge. A local PHP response proves only what the origin emitted.

Use Vary when a request header legitimately selects the representation, and ensure your CDN supports the intended behavior. Do not assume Vary: Cookie makes a personalized page safe to cache publicly. Bypassing shared caching for authenticated routes is often easier to reason about.

Keep hashed static assets on a longer immutable policy and HTML on a policy compatible with your publishing requirements. A long HTML freshness window delays visible updates unless you have a reliable invalidation strategy.

Test correctness before measuring speed

Request the page without a condition, repeat with its ETag, then change the representation and repeat with the old ETag. Verify the 200 and 304 paths and that a 304 response has no body. Test HEAD separately.

Use two authenticated users when checking personalized routes. Inspect Cache-Control, Vary, Set-Cookie, Age, and provider-specific cache indicators. Never infer a hit solely from a fast timing.

See PHP performance bottlenecks for the broader measurement process, or discuss a caching review before changing shared-cache rules.