zoukankan      html  css  js  c++  java
  • php静态文件返回304

    有时一些静态文件(如图片)会由php输出,会发现请求都是200,静态文件每次都去服务器上请求太浪费资源了,这时如何让浏览器缓存图片呢?就需要我们在php中输出304了。

    我们可以利用php中的 HTTP_IF_MODIFIED_SINCE 结合etag来干这事。Etag没有明确规定的格式,我们可以用文件修改时间的md5值,代码如下:

    private function _addEtag($file) {
        $last_modified_time = filemtime($file); 
        $etag = md5_file($file);
        // always send headers 
        header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
        header("Etag: $etag"); 
        // exit if not modified
        if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || 
        @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { 
            header("HTTP/1.1 304 Not Modified"); 
            exit; 
        }
    }

    上面那段代码有时不太好使,有下面这段:

    private function _addEtag($file) {
            $last_modified_time = filemtime($file);
            $gmt_mtime = gmdate('r', $last_modified_time);
            header('ETag: "'.md5($last_modified_time.$file).'"');
            header('Last-Modified: '.$gmt_mtime);
            header('Cache-Control: public');
    
            if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
                if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime || str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == md5($last_modified_time.$file)) {
                    header('HTTP/1.1 304 Not Modified');
                    exit();
                }
            }
        }

    在代码中可以在静态文件(如图片)输出之前调用即可。

  • 相关阅读:
    HDU 2955 Robberies(01背包)
    HDU 2602 Bone Collector(01背包)
    HUST 1352 Repetitions of Substrings(字符串)
    HUST 1358 Uiwurerirexb jeqvad(模拟解密)
    HUST 1404 Hamming Distance(字符串)
    HDU 4520 小Q系列故事――最佳裁判(STL)
    HDU 2058 The sum problem(枚举)
    【破解】修改程序版权、添加弹窗
    HDU 1407 测试你是否和LTC水平一样高(枚举)
    HDU 1050 Moving Tables(贪心)
  • 原文地址:https://www.cnblogs.com/lurenjiashuo/p/php-response-304.html
Copyright © 2011-2022 走看看