如何缓存通过 PHP 提供的图像?

Cli*_*ote 1 php caching header

我将网站的背景图像设置为服务器上的 url,这是一个 php 脚本,并提供图像作为其输出。这是它的代码:

   //$mime is usually image/jpeg, etc
   header("Content-type: $mime");
   $image = readfile($image);
   imagejpeg($image);
Run Code Online (Sandbox Code Playgroud)

问题是,每次加载页面时,图像似乎都会再次加载而不是被缓存。我能做些什么吗,例如发送标头来缓存图像?

Mih*_*rga 5

我总是使用 ETag(md5哈希值)和 Last-Modified(过去的日期,通常是创建文件时)获得最佳结果。

对于你的代码它将是这样的:

$etag = md5_file($image);
$lastModified = gmdate('D, d M Y H:i:s', filemtime($image)) . ' GMT';


header("Content-type: $mime");
header("ETag: \"{$etag}\"");
header("Last-Modified: $lastModified");
header('Expires: ' . gmdate("D, d M Y H:i:s", ((60*60*24*45)+strtotime($lastModified)))); // add 45 days expire

$image = readfile($image);
imagejpeg($image);
Run Code Online (Sandbox Code Playgroud)