PHP curl无法正确处理图像

时间:2010-11-29 17:16:26

标签: php curl gd libcurl

我有一个内部代理,从我自己的服务器获取数据并显示给客户端。我想保持代理端代码最小化,并认为只是将内容服务器上的数据发送到客户端将适用于所有媒体类型。它适用于HTML / TEXT代码。但是,不适用于图像。我无法理解为什么。

以下是代理端代码:

$curl_url="http//myserver.com/someimage.jpg";
//Open connection
$curl_handle = curl_init();
curl_setopt($curl_handle,CURLOPT_COOKIE,session_name()."=".session_id().";");
//Set the url, number of POST vars, POST data
curl_setopt($curl_handle, CURLOPT_URL, $curl_url);
curl_setopt($curl_handle, CURLOPT_POST, count($_POST));
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $_POST);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($curl_handle, CURLOPT_HEADER, 0);
/// curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $curl_request_headers);
/// Above is actually uncommented but omitting details for brevity. They are just 
/// HTTP headers passed by the client
curl_setopt($curl_handle, CURLOPT_ENCODING, "identity");

//Execute post
$result = curl_exec($curl_handle);

//Close connection
curl_close($curl_handle);

echo $result;

为什么上面没有正确显示图像? (是否不可能使代理像虚拟桥接器一样 - 它不会解释服务器发送的结果,而只是将其传递并仍使其适用于所有内容/媒体类型?)。有人可以建议最干净的解决方案吗?


注意:

1)内容服务器通过php脚本处理所有文件,并使用正确传递标头  header('Content-Type: image/jpeg');

如果我直接从服务器访问它可以正常工作。但是,从代理中,它不起作用(浏览器显示二进制数据)。

2) 我也不太了解CURLOPT_HEADER。

如果我使用

curl_setopt($curl_handle, CURLOPT_HEADER, 1);

浏览器尝试下载gzip压缩数据(用于文本和图像)。

如果我使用

curl_setopt($curl_handle, CURLOPT_HEADER, 0);

浏览器正确显示文本/图像,但不显示图像数据。


当我通过代理(直接链接)在浏览器中访问图像时,这些是Google Chrome显示的响应标题。

Response Headers
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Encoding:gzip
Content-Length:2576
Content-Type:text/html
Date:Mon, 29 Nov 2010 18:03:52 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=15, max=100
Pragma:no-cache
Server:Apache/2.2.14 (Ubuntu)
Vary:Accept-Encoding
X-Powered-By:PHP/5.3.2-1ubuntu4.5

直接在内容服务器上访问图像时的响应标头:

Accept-Ranges:bytes
Connection:Keep-Alive
Content-Length:3669
Content-Type:image/jpeg
Date:Mon, 29 Nov 2010 18:07:25 GMT
ETag:"1802b6-e55-49633c9623e40"
Keep-Alive:timeout=15, max=96
Last-Modified:Mon, 29 Nov 2010 16:44:33 GMT
Server:Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.6 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g

我觉得这是因为Content-type是通过代理GZIP。有人可以请帮助我理解这一点:默认情况下,图像不是由apache GZIPPed吗? (我同意节省可能会减少)。如果没有,那么CURL(代理)Gzipping数据?不应该CURLOPT_ENCODING,“身份”阻止吗?我该如何解决?

2 个答案:

答案 0 :(得分:1)

您需要使用header发送正确的标头,告诉浏览器正确的内容类型,否则它假定它只是纯文本。

答案 1 :(得分:0)

嗯,你通过Curl将图像作为字符串获取,所以当你回显$ result时,你打印的是图像的数据,而不是渲染<img src="..." />