zoukankan      html  css  js  c++  java
  • php header()函数设置页面Cache缓存

    header()函数在php的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使用header前必须注意,在它之前不能任何输出,包括空格。

    手册上,我们对于cache都是写着如何设置,以便让代码不被cache:

    header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
    header("Pragma: no-cache"); // Date in the past
    

    而且在设置的时候还得注意在header前不能有输出,否则header设置无效,但都没有写过,如何给页面设置Cache,虽然我们知道有一些办法,比如 E-TAG之类的。当然也有简单的设置:

    比如我们在输出前,对内容进行md5,将它当成e-tag只要没变化,就不会有影响。也有其他的方式:

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

    缓存1小时,主要是过期时间得用gmdate来设置,而不是date,这个要注意,其他都差不多。maxage要和expire能够对得上。

    对于PHP产生的动态内容,只需要在内容输出之前输出强制缓存的header即可,比如下面的代码即要求浏览器缓存文件1个月:

    <?php
      header("Cache-Control: public");
      header("Pragma: cache");
    
      $offset = 30*60*60*24; // cache 1 month
      $ExpStr = "Expires: ".gmdate("D, d M Y H:i:s", time() + $offset)." GMT";
      header($ExpStr);
    ?>
    

    对于静态文件,一般的服务器都支持第3级缓存状态。要想达到第四级的缓存效果,要么像之前GZIP压缩那样,用PHP外包一层,然后用PHP处理。要么需 要服务器端的支持,APACHE的一个模块mod_expires支持给文件添加expires header。把下面的代码加入你的blog目录下的.htaccess文件,如果你的服务器安装了mod_expires模块,则将自动生效,图片等强 制缓存一个月,html文档缓存10分钟。如果该模块没有安装,也不会出错。

    <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/gif A2592000
    ExpiresByType image/jpeg A2592000
    ExpiresByType image/png A2592000
    ExpiresByType application/x-shockwave-flash A2592000
    ExpiresByType text/css A2592000
    ExpiresByType application/x-javascript A2592000
    ExpiresByType text/html A600
    </IfModule>
    

     在这里有mod_expires更详细的文档和教程。不过我要说明的是,mod_expires在绝大多数服务器上都没安装

  • 相关阅读:
    Balanced Binary Tree
    Swap Nodes in Pairs
    Reverse Nodes in k-Group
    Reverse Linked List II
    Remove Nth Node From End of List
    Remove Duplicates from Sorted List II
    Remove Duplicates from Sorted List
    Partition List
    Merge Two Sorted Lists
    【Yii2.0】1.2 Apache检查配置文件语法
  • 原文地址:https://www.cnblogs.com/phpxuetang/p/5025577.html
Copyright © 2011-2022 走看看