如何在PHP文件中使用ETags?

23

你如何在PHP文件中实现ETags?我需要上传什么到服务器,以及将什么插入我的PHP文件中?

2个回答

43

创建/编辑.htaccess文件并添加以下内容:

FileETag MTime Size

将以下内容放在函数内,或者放在你需要启用ETags的PHP文件顶部:

Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:
<?php 
    $file = 'myfile.php';
    $last_modified_time = filemtime($file); 
    $etag = md5_file($file); 

    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
    header("Etag: $etag"); 

    if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || 
        trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { 
        header("HTTP/1.1 304 Not Modified"); 
    exit; 
} 
?>

我遇到过这样的情况,需要修剪 $_SERVER['HTTP_IF_NONE_MATCH'] 中周围的单引号/双引号。 - Svetoslav Marinov
@lordspace 是什么情况?这会导致脚本无法工作吗? - Nagra
我记不得我当时在处理哪个产品,但是etag字符串被双引号包围,所以我必须使用trim($etag, '"'');。 - Svetoslav Marinov
9
请注意,这仅适用于PHP文件不包含其他文件的情况。因为更新其他文件不会改变ETag。 - vallentin
2
Etag值必须包含引号,https://datatracker.ietf.org/doc/html/rfc7232#section-2.3 - Mihail H.

3

对应于https://datatracker.ietf.org/doc/html/rfc7232#section-2.3的版本(etag值必须带引号):

<?php
$file = __DIR__ . '/myfile.js';
$etag = '"' . filemtime($file) . '"';

// Use it if the file is changed more often than one time per second:
// $etag = '"' . md5_file($file) . '"';

header('Etag: ' . $etag);

$ifNoneMatch = array_map('trim', explode(',', trim($_SERVER['HTTP_IF_NONE_MATCH'])));
if (in_array($etag, $ifNoneMatch, true) || count($ifNoneMatch) == 1 && in_array('*', $ifNoneMatch, true)) {
    header('HTTP/1.1 304 Not Modified');
    exit;
}

print file_get_contents($file);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接