繁体   English   中英

PHP curl无法正确处理图像

[英]PHP curl not handling images properly

我有一个内部代理,可从我自己的服务器中获取数据并显示给客户端。 我想将代理端代码保持在最小限度,并认为仅将从内容服务器获取的数据按原样发送到客户端就可以适用于所有媒体类型。 对于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');正确传递标题header('Content-Type: image/jpeg');

如果我直接从服务器访问,效果很好。 但是,从代理开始,它不起作用(浏览器显示二进制数据)。

2)我对CURLOPT_HEADER也不太了解。

如果我用

curl_setopt($curl_handle, CURLOPT_HEADER, 1);

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

如果我用

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(代理)是否在压缩数据? CURLOPT_ENCODING是否应该阻止“身份”? 我该如何解决?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM