Question

How do you implemented etags inside a PHP file? What do I upload to the server and what do I insert into my PHP file?

Was it helpful?

Solution

Create / edit your .htaccess file and add the following:

FileETag MTime Size

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; 
} 
?>

OTHER TIPS

Version that corresponding to https://datatracker.ietf.org/doc/html/rfc7232#section-2.3 (an etag value must be quoted):

<?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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top