Mastering HTTP Cache Headers for Dynamic PHP Content
Many developers assume that because PHP generates HTML dynamically, caching is impossible without a framework or an in-memory store like APC. This is a misconception. Even if your hosting environment lacks APCu, Memcached, or Redis, you can still leverage the browser cache effectively by configuring HTTP response headers correctly. The goal isn't to store every page on the server for later retrieval (though that is possible with file-based caching), but rather to tell the client when content has changed so they don't waste bandwidth fetching stale data.
To make this work, you must understand that "static" in your scenario refers to the payload remaining unchanged while the template or language might shift. This nuance dictates which headers are mandatory versus optional. If you simply set a long expiration time without addressing conditional requests or content negotiation, you risk serving outdated templates to users who have recently updated their site's layout.
The Foundation: Vary and Accept-Language
Your current implementation uses header('Vary: Accept') and Content-language. These are excellent choices for dynamic sites where the same URL might return different payloads based on the user agent or locale. However, relying solely on these is often insufficient for a robust caching strategy.
If you want to cache pages for up to 180 seconds (as suggested by your session_cache_expire setting), you need to pair that with an expiration directive. Without Cache-Control, modern browsers and intermediate proxies like Varnish or Nginx will ignore any attempt to set a maximum age, defaulting to aggressive caching behaviors or no caching at all depending on the server configuration.
You should implement Cache-Control: max-age=180 alongside your existing logic. This explicitly tells compliant clients that the resource is fresh for 180 seconds. If you are unsure about the client's capabilities, adding public ensures that external caches (like CDN nodes or shared proxy servers) can also store the response, significantly reducing load on your PHP application server.
Handling Conditional Requests
The most powerful aspect of HTTP caching is not just storing data, but validating it. When a user revisits a page within the cache window, your server should still respond with 200 OK to confirm freshness, but ideally, you want to use conditional requests to minimize bandwidth.
Browsers will automatically send If-Modified-Since or If-None-Match headers for cached resources. Your PHP script must check these before generating content. If the resource hasn't changed since the last ETag was issued (or since the Last-Modified time), you can return a 304 Not Modified status immediately, sending zero bytes over the network.
Implementing this in raw PHP requires careful handling of headers to ensure they are set before any output is sent. You can determine if a resource has changed by comparing the current timestamp against the stored modification time or by generating an ETag based on your application's state. If the client provides a matching If-None-Match, return the 304 status immediately:
if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$lastModified = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
// Compare file timestamps or database version here
if ($resourceIsUnchanged) {
http_response_code(304);
exit;
}
}
if (!empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
$etag = generateETag();
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && hash_equals($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) {
http_response_code(304);
exit;
}
}
Addressing the Template Change Problem
Your specific challenge is that the "template" changes over time while content remains static. This creates a conflict: if you cache aggressively, users might see an old template rendering new content. To mitigate this, ensure your Vary header includes any parameters that influence the template selection. If your application logic determines the template based on a specific query parameter or cookie, add those to the Vary header.
For example, if you serve different templates for logged-in versus logged-out users, your Vary header should include Authorization or Cookie. Failing to do so results in incorrect responses being cached globally, leading to security leaks or UI inconsistencies.
Session Caching Considerations
You are currently using session_cache_limiter('private'). This is generally correct for user-specific data, but remember that session regeneration or expiration logic happens on the server side. Setting a long expiration on the session itself does not automatically extend the HTTP cache lifetime of the rendered HTML. The two concepts are distinct: one manages server-side state storage duration, the other manages client-side response caching. Ensure you are not conflating these; setting session_cache_expire to 180 seconds only affects how long PHP keeps the session data in memory before discarding it, not how long the browser caches your HTML output.
For a robust solution on shared hosting without APC, consider moving towards file-based caching if dynamic template changes are infrequent enough to tolerate a brief flush cycle. However, strictly adhering to HTTP headers remains the most portable and standard-compliant approach for immediate needs.