如何在PHP文件中使用etags?

时间:2012-11-02 14:43:25

标签: php caching header etag

如何在PHP文件中实现etags?我上传到服务器的内容以及我将什么内容插入到我的PHP文件中?

2 个答案:

答案 0 :(得分:36)

创建/编辑.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; 
} 
?>

答案 1 :(得分:0)

对应于 {{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);
相关问题