txid
txid

Reputation: 66

How to cache script returned via PHP

I need to return script to user if he is accepted. It is too long to check user, and i want return 304 Not modified. I have simple code to check, but it don't work. Browser do not resquest If-Modified-Since. If it were source *.js extentsion, it could be script.js?ver=1.0 for example? but not with *.php Is this way write or there is another one?

html code:

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

php code:

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

Browser request (not first):

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: ...

Upvotes: 0

Views: 62

Answers (1)

Huy Nguyen
Huy Nguyen

Reputation: 2061

About your case, i think you can apply some rewrite rule in htaccess or server configuration: For example:

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

Upvotes: 1

Related Questions