Home  >  Article  >  Backend Development  >  How can I effectively leverage HTTP headers for caching with PHP?

How can I effectively leverage HTTP headers for caching with PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 03:03:29941browse

How can I effectively leverage HTTP headers for caching with PHP?

Understanding HTTP Caching with PHP Headers

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:

  • Vary: This header specifies that the content varies based on parameters like language or user agent, ensuring browsers retrieve the appropriate cached version.
  • Last-Modified: Indicates the last time the content was modified. Browsers compare this value to the If-Modified-Since header in subsequent requests to determine if content needs to be refreshed.
  • ETag: This header represents an entity tag or checksum of the content. Browsers compare this value to the If-None-Match header to avoid re-requesting unchanged content.

Implementation:

  1. Set Cache Policy:

    <code class="php">session_cache_limiter('private_no_expire'); // Allow caching but do not reveal cache expiry time</code>
  2. Set Expiration:

    <code class="php">header("Cache-Control: max-age=" . (60 * 60 * 24 * 30)); // Set cache expiration to 30 days</code>
  3. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn