Q: What HTTP headers are essential for effective caching with PHP?
A: When implementing HTTP caching for a website, specific headers play a crucial role in guiding browsers on how to manage cached content. Essential headers include:
Implementation:
Set Cache Policy:
<code class="php">session_cache_limiter('private_no_expire'); // Allow caching but do not reveal cache expiry time</code>
Set Expiration:
<code class="php">header("Cache-Control: max-age=" . (60 * 60 * 24 * 30)); // Set cache expiration to 30 days</code>
Manage If-Modified-Since and If-None-Match Headers:
Compare the values of these headers to the Last-Modified and ETag headers to avoid unnecessary re-requests:
<code class="php">$tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT'; $etag = $language . $timestamp; $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false; $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false; if ((($if_none_match && $if_none_match == $etag) || (!$if_none_match)) && ($if_modified_since && $if_modified_since == $tsstring)) { header('HTTP/1.1 304 Not Modified'); exit(); } else { header("Last-Modified: $tsstring"); header("ETag: \"{$etag}\""); }</code>
The above is the detailed content of How can I effectively leverage HTTP headers for caching with PHP?. For more information, please follow other related articles on the PHP Chinese website!