如何缓存通过PHP提供的图像? [英] How to cache an image being served through PHP?
问题描述
我将我网站的背景图像设置为服务器上的一个url,这是一个php脚本,它将图像作为输出。这里是它的代码:
$ $ $ $ mime通常是image / jpeg等
header(Content -type:$ mime);
$ image = readfile($ image);
imagejpeg($ image);
问题在于,每当我加载我的页面时,图片似乎都会再次加载,而不是缓存。有什么我可以做的,例如发送一个头缓存图像?
我总是得到最好的结果ETag( md5
hash)和Last-Modified(过去的日期,通常是在创建文件时)。
<对于你的代码,它会是这样的:
$ etag = md5_file($ image);
$ lastModified = gmdate('D,d M Y H:i:s',filemtime($ image))。 ' 格林威治标准时间';
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)))); //添加45天过期
$ image = readfile($ image);
imagejpeg($ image);
I'm setting the background-image of my website to a url on the server, which is a php script and which serves an image as its output. Here is the code for it:
//$mime is usually image/jpeg, etc
header("Content-type: $mime");
$image = readfile($image);
imagejpeg($image);
The issue is, each time I load my page, the image seems to be loaded again rather than being cached. Is there anything I can do about that, e.g to send a header to cache the image?
I always get best results using the ETag (a md5
hash) and Last-Modified (a past date, usually when the file was created).
for your code it will be like this:
$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);
这篇关于如何缓存通过PHP提供的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!