Programing

PHP에서 HTTP 캐시 헤더를 사용하는 방법

lottogame 2020. 12. 9. 07:38
반응형

PHP에서 HTTP 캐시 헤더를 사용하는 방법


PHP 5.1.0 웹 사이트가 있습니다 (실제로 5.2.9이지만 5.1.0 이상에서도 실행되어야합니다).

페이지는 동적으로 생성되지만 대부분은 대부분 정적입니다. 정적이란 콘텐츠는 변경되지 않지만 콘텐츠 주변의 "템플릿"은 시간이 지남에 따라 변경 될 수 있음을 의미합니다.

이미 여러 캐시 시스템과 PHP 프레임 워크라는 것을 알고 있지만 호스트에는 APC 또는 Memcached가 설치되어 있지 않으며이 특정 프로젝트에 대해 프레임 워크를 사용하지 않습니다.

페이지가 캐시되기를 원합니다 (기본적으로 PHP "disallow"캐시). 지금까지 사용하고 있습니다.

session_cache_limiter('private'); //Aim at 'public'
session_cache_expire(180);
header("Content-type: $documentMimeType; charset=$documentCharset");
header('Vary: Accept');
header("Content-language: $currentLanguage");

나는 많은 튜토리얼을 읽었지만 간단한 것을 찾을 수 없습니다 (캐시가 복잡한 것을 알고 있지만 기본적인 것 만 필요합니다).

캐싱을 돕기 위해 보내야하는 "필수"헤더는 무엇입니까?


private_no_expire대신을 ( 를) 사용하고 싶을 수 private있지만 변경되지 않을 것임을 알고있는 콘텐츠에 대해 긴 만료 시간을 설정하고 Emil의 게시물과 유사한 처리 if-modified-sinceif-none-match요청 을 확인하십시오 .

$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}\"");
}

$etag콘텐츠 또는 사용자 ID, 언어 및 타임 스탬프를 기반으로 한 체크섬은 어디에 있습니까?

$etag = md5($language . $timestamp);

Expires 헤더가 있어야합니다. 기술적으로 다른 솔루션이 있지만 Expires 헤더는 만료 날짜 및 시간 전에 페이지를 다시 확인하지 않고 캐시에서 콘텐츠를 제공하도록 브라우저에 지시하기 때문에 실제로 가장 좋은 솔루션입니다. 정말 훌륭하게 작동합니다!

브라우저의 요청에서 If-Modified-Since 헤더를 확인하는 것도 유용합니다. 이 헤더는 캐시의 콘텐츠가 여전히 올바른 버전인지 브라우저가 "확실하지 않은"경우 전송됩니다. 그 이후로 페이지가 수정되지 않은 경우 HTTP 304 코드 (수정되지 않음)를 다시 보내십시오. 다음은 10 분 동안 304 코드를 보내는 예입니다.

<?php
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  if(strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) < time() - 600) {
    header('HTTP/1.1 304 Not Modified');
    exit;
  }
}
?>

서버 리소스를 절약하기 위해 코드 초기에이 검사를 수행 할 수 있습니다.


<?php
header("Expires: Sat, 26 Jul 2020 05:00:00 GMT"); // Date in the future
?>

캐시 된 페이지의 만료 날짜를 설정하는 것은 클라이언트 측에서 캐시하는 유용한 방법 중 하나입니다.


선택하거나 모두 사용하십시오! :-)

header ( '만료 : Thu, 01-Jan-70 00:00:01 GMT');
header ( '마지막 수정 :'. gmdate ( 'D, d MYH : i : s'). 'GMT');
header ( 'Cache-Control : no-store, no-cache, must-revalidate');
header ( 'Cache-Control : post-check = 0, pre-check = 0', false);
header('Pragma: no-cache');

Here's a small class that does http caching for you. It has a static function called 'Init' that needs 2 parameters, a timestamp of the date that the page (or any other file requested by the browser) was last modified and the maximum age, in seconds, that this page can be held in cache by the browser.

class HttpCache 
{
    public static function Init($lastModifiedTimestamp, $maxAge)
    {
        if (self::IsModifiedSince($lastModifiedTimestamp))
        {
            self::SetLastModifiedHeader($lastModifiedTimestamp, $maxAge);
        }
        else 
        {
            self::SetNotModifiedHeader($maxAge);
        }
    }

    private static function IsModifiedSince($lastModifiedTimestamp)
    {
        $allHeaders = getallheaders();

        if (array_key_exists("If-Modified-Since", $allHeaders))
        {
            $gmtSinceDate = $allHeaders["If-Modified-Since"];
            $sinceTimestamp = strtotime($gmtSinceDate);

            // Can the browser get it from the cache?
            if ($sinceTimestamp != false && $lastModifiedTimestamp <= $sinceTimestamp)
            {
                return false;
            }
        }

        return true;
    }

    private static function SetNotModifiedHeader($maxAge)
    {
        // Set headers
        header("HTTP/1.1 304 Not Modified", true);
        header("Cache-Control: public, max-age=$maxAge", true);
        die();
    }

    private static function SetLastModifiedHeader($lastModifiedTimestamp, $maxAge)
    {
        // Fetching the last modified time of the XML file
        $date = gmdate("D, j M Y H:i:s", $lastModifiedTimestamp)." GMT";

        // Set headers
        header("HTTP/1.1 200 OK", true);
        header("Cache-Control: public, max-age=$maxAge", true);
        header("Last-Modified: $date", true);
    }
}

I was doing JSON caching at the server coming from Facebook feed nothing was working until I put flush and hid error reporting. I know this is not ideal code, but wanted a quick fix.

error_reporting(0);
    $headers = apache_request_headers();
    //print_r($headers);
    $timestamp = time();
    $tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
    $etag = md5($timestamp);
    header("Last-Modified: $tsstring");
    header("ETag: \"{$etag}\"");
    header('Expires: Thu, 01-Jan-70 00:00:01 GMT');

    if(isset($headers['If-Modified-Since'])) {
            //echo 'set modified header';
            if(intval(time()) - intval(strtotime($headers['IF-MODIFIED-SINCE'])) < 300) {
              header('HTTP/1.1 304 Not Modified');
              exit();
            }
    }
    flush();
//JSON OP HERE

This worked very well.


This is the best solution for php cache Just use this in the top of the script

$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");

참고URL : https://stackoverflow.com/questions/1971721/how-to-use-http-cache-headers-with-php

반응형