通过PHP缓存图像请求 - 如果 - 已修改 - 自未发送

Lou*_*s W 5 php apache caching header

我正在通过PHP提供图像,并设置一些问题,以回应304标头,以节省加载时间.

我在php.net上找到的大部分代码.它工作,但总是以200响应.由于某种原因,即使我最初发送Last-Modified标头,也没有在任何请求上收到If-Modified-Since标头.这是在Apache服务器上完成的.知道什么可能是错的吗?

这里的例子.

此页面将从磁盘加载图像并将其显示到浏览器,同时发送Last-Modified标头.如果刷新页面,浏览器不会像它应该发送If-Modified-Since标头.

define('SITEPATH', (dirname($_SERVER['SCRIPT_NAME']) == '/') ? '/' : dirname($_SERVER['SCRIPT_NAME']).'/');

$load_path = $_SERVER['DOCUMENT_ROOT'] . SITEPATH . 'fpo_image.jpg';

// Get headers sent by the client.
$headers    = apache_request_headers(); 
$file_time  = filemtime($load_path);

header('Cache-Control: must-revalidate');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $file_time).' GMT');

if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $file_time)) {

    header('HTTP/1.1 304 Not Modified');
    header('Connection: close');

} else {

    header('HTTP/1.1 200 OK');
    header('Content-Length: '. filesize($load_path));
    header('Content-type: image/jpeg');                         

    readfile($load_path);

}
Run Code Online (Sandbox Code Playgroud)

Kei*_*itt 5

mandor dot net的mandor在 PHP.net文档中发布了一个解决方案,用于头函数,这对我有用:

<?php

        // Test image.
        $fn = '/test/foo.png';

        // Getting headers sent by the client.
        $headers = apache_request_headers();

        // Checking if the client is validating his cache and if it is current.
        if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
            // Client's cache IS current, so we just respond '304 Not Modified'.
            header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
        } else {
            // Image not cached or cache outdated, we respond '200 OK' and output the image.
            header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
            header('Content-Length: '.filesize($fn));
            header('Content-Type: image/png');
            print file_get_contents($fn);
        }

    ?>
Run Code Online (Sandbox Code Playgroud)


小智 2

我相信应该是

if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) >= $file_time)) {
Run Code Online (Sandbox Code Playgroud)

检查修改时间是否大于或等于而不仅仅是等于。虽然我确实理解这两个值应该是相同的。