Conventional Caching

    Today I decided to do what I was planning for a long time - to put the caching of scripts on my site. All scripts are collected in a single file before being sent to the user and compressed by GZIP — everything seems to be smart, but there is a problem ... The browser desperately did not want to cache this output script.

    It has been experimentally established that PHP sets cache prohibition headers when using the session_start () function ;

    Here is an example of code that implements caching of a specific file (note the three header () functions that remove extra headers):

    1. session_start(); // где-то вверху начинается сессия
    2.  
    3.  
    4. function cmsCache_control($file, $time) {
    5.   
    6.   $etag = md5_file($file);
    7.   $expr = 60 * 60 * 24 * 7;
    8.   
    9.   header("ETAG: " . $etag);
    10.   header("LAST-MODIFIED: " . gmdate("D, d M Y H:i:s", $time) . " GMT");
    11.   header("CACHE-CONTROL: ");
    12.   header("PRAGMA: ");
    13.   header("EXPIRES: ");
    14.   
    15.   if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
    16.     
    17.     $if_modified_since = preg_replace("/;.*$/", "", $_SERVER["HTTP_IF_MODIFIED_SINCE"]);
    18.     
    19.     if(trim($_SERVER["HTTP_IF_NONE_MATCH"]) == $etag && $if_modified_since == gmdate("D, d M Y H:i:s", $time). " GMT") {
    20.       
    21.       header("HTTP/1.0 304 Not modified");
    22.       header("CACHE-CONTROL: MAX-AGE={$expr}, MUST-REVALIDATE");
    23.       exit;
    24.       
    25.     }
    26.     
    27.   }
    28.   
    29. }
    30.  
    31.  
    32. cmsCache_control($_SERVER[SCRIPT_FILENAME], filemtime($_SERVER[SCRIPT_FILENAME]));
    33. //дальше обычный вывод того, что кешируем
    * This source code was highlighted with Source Code Highlighter.


    The script does nothing special - it simply sets the modification date in the header, and then it follows the standard request headers for what date the cached file has.

    The only addition is that instead of filemtime (), you can also use another arbitrary date, in my script I used the date the most recent file was changed.

    PS The above fragment was modified by me to take into account the sessions, but the code itself is taken from here: http://ru2.php.net/manual/ru/function.header.php#85146 , as well as http://foxweb.net.ru /texts/43.htm (comments comrade antishock ).

    Also popular now: