代码之家  ›  专栏  ›  技术社区  ›  txid

如何缓存通过PHP返回的脚本

  •  0
  • txid  · 技术社区  · 7 年前

    我需要返回脚本给用户,如果他被接受。它太长,无法检查用户,我希望返回304未修改。我有简单的代码要检查,但它不起作用。浏览器自修改后不重新请求。如果它是源*。js扩展,可能是脚本。js?例如,ver=1.0?但不适用于*。php 是这样写的还是有另一种?

    html代码:

    <script src="get_secret_script.php"></script>
    

    php代码:

    $script_name = "./script.js";
    $last_modified = filemtime($script_name);
    $etag = hash_file('crc32b', $script_name);
    header("Content-Type: text/javascript");
    
    //header("Etag: $etag");
    
    // Condition not met, there is no $_SERVER['HTTP_IF_MODIFIED_SINCE']
    // in browser request
    if(@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified)
    {
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", $last_modified) . " GMT", true, 304);  
        exit;
    }
    
    $fp = fopen($script_name, 'r'); 
    header("Last-Modified: " . gmdate("D, d M Y H:i:s", $last_modified) . " GMT", true, 200);
    header("Content-Length: " . filesize($script_name));
    
    fpassthru($fp); 
    exit;
    

    浏览器请求(不是第一个):

    GET /test/get_secret_script.php HTTP/1.1
    Host: 127.0.0.1
    Connection: keep-alive
    User-Agent: Browser identity string
    Accept: */*
    Referer: http://127.0.0.1/test/test.html
    Accept-Encoding: gzip, deflate, br
    Accept-Language: ...
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Huy Nguyen    7 年前

    关于您的案例,我认为您可以在htaccess或服务器配置中应用一些重写规则: 例如:

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase  /
        RewriteRule ^script.js get_secret_script.php[NC,L]
    </IfModule>