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

时间:2018-01-12 04:21:24

标签: php web browser webserver browser-cache

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

1 个答案:

答案 0 :(得分:1)

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

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