22

您如何在 PHP 文件中实现 etags?我要上传什么到服务器,我要在我的 PHP 文件中插入什么?

4

2 回答 2

41

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

FileETag MTime Size

将以下内容放在函数中或将其放在需要 etags 处理的 PHP 文件的顶部:

<?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; 
} 
?>
于 2012-11-02T14:43:25.073 回答
0

对应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);
于 2021-05-15T23:08:30.387 回答