【问题标题】:How to cache script returned via PHP如何缓存通过 PHP 返回的脚本
【发布时间】:2018-06-21 12:25:50
【问题描述】:

如果他被接受,我需要将脚本返回给用户。检查用户太长,我想返回 304 未修改。我有简单的代码要检查,但它不起作用。浏览器不请求 If-Modified-Since。如果它是 source *.js 扩展,它可能是 script.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: ...

【问题讨论】:

    标签: php web browser webserver browser-cache


    【解决方案1】:

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

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

    【讨论】:

    • 在 get_secret_script.php 我需要检查这个用户是否可以访问这个脚本。如果我要写这个,它会将脚本返回给所有用户。对吗?
    • 不,重写规则只是简单地更改 url。例如:^script.js get_secret_script.php[NC,L] 当满足请求的script.js时,会处理get_secret_script.php。您可以测试和调试一些重写规则并查看结果。
    • 如果想保存 secret.js?123456 之类的参数 -> get_secret_script.php?id=123456?
    • 所有参数也将以相同的名称转发。我认为你应该更改js文件中的参数:secret.js?ver=12345 所以在php中,你也可以检索这个参数并做你的事情,或者你可以自定义重写规则。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2012-10-12
    • 2011-02-22
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    相关资源
    最近更新 更多