php http 缓存,如何在PHP中使用HTTP缓存头

24836f1df5fee55455bdc7932fa84bfb.png

拉丁的传说

这是一个为您执行http缓存的小类。它有一个名为“ Init”的静态函数,它需要2个参数,该页面(或浏览器请求的任何其他文件)的最后修改日期的时间戳,以及该页面可以保留的最大期限(以秒为单位)。浏览器缓存。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);    }}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值