我有一个PHP脚本,它通过?img=参数调用。
该参数的值是一个被URL编码的图片URL。
我的脚本检查是否已经在我的服务器上存储了该图片。
如果没有-它会下载它。之后,它可选地调整图像大小并将其发送到STDOUT,即返回给请求浏览器,附加了Content-Type和Last-modified头:
Connection:close
Content-Type:image/jpeg
Date:Fri, 01 Jun 2012 08:28:30 GMT
Last-Modified:Fri, 01 Jun 2012 08:02:44 GMT
Server:Apache/2.2.15 (CentOS)
Transfer-Encoding:chunked
X-Powered-By:PHP/5.3.3
为了解决一些跨域问题,我需要这个方法。在过去一年中,它为我提供了很好的效果:
但是现在我想添加处理If-Modified-since头的功能 - 发送一个Not Modified 304响应。
我的问题如下:
1)在Apache中运行的PHP是否可以实现这一点?
2)最好如何在PHP中处理(即解析和生成)日期?
附加问题)如何为缩小后的图像添加Content-Length头?
以下是我的代码(我省略了CURL下载部分):
<?php
define('CACHE_DIR', '/var/www/cached_avatars/');
$img = urldecode($_GET['img']);
$cached = CACHE_DIR . md5($img);
# omitted downloading part for brevity
$readfh = fopen($cached, 'rb');
if ($readfh) {
flock($readfh, LOCK_SH);
$size = getimagesize($cached);
$w = $size[0];
$h = $size[1];
$type = $size[2];
$mime = $size['mime'];
# find the downscale factor to fit image into $maxw x $maxh
$scale = max($w / $maxw, $h / $maxh);
header('Content-Type: ' . $size['mime']);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($cached)));
$length = filesize($cached);
$buf = fread($readfh, $length);
fclose($readfh);
# the image is smaller than $maxw x $maxh, do not scale up
if ($scale <= 1) {
header('Content-Length: ' . $length);
print($buf);
return;
}
$tw = $w / $scale;
$th = $h / $scale;
$image = imagecreatefromstring($buf);
$thumb = imagecreatetruecolor($tw, $th);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $tw, $th, $w, $h);
imagedestroy($image);
# How to add Content-Length here, after image resizing?
if (IMAGETYPE_JPEG == $type)
imagejpeg($thumb, null, 75);
else if (IMAGETYPE_PNG == $type)
imagepng($thumb, null, 9);
else if (IMAGETYPE_GIF == $type)
imagegif($thumb, null);
imagedestroy($thumb);
}
?>
$mod = gmdate('D, d M Y H:i:s T', filemtime($cached)); if (@$_SERVER['HTTP_IF_MODIFIED_SINCE'] == $mod) { header('HTTP/1.0 304 Not Modified'); exit; }
- Alexander Farber