php - 如何在 php 中显示来自 curl 的二进制数据

标签 php image curl binary-data

我正在编写简单的 php 代理,我无法显示 png 文件,输出是

enter image description here

应该是:

enter image description here

图像在 Notepad++ 中打开。我的 php curl 代码如下所示:

$ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
curl_setopt($ch, CURLOPT_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$content = curl_exec($ch);
$info = curl_getinfo($ch);
header('Content-Type:' . $info['content_type']);
echo $content

我尝试使用和不使用 CURLOPT_BINARYTRANSFER,输出是相同的并且图像不显示。如何显示图像?

编辑:当我将数据保存到文件并使用 Location header 重定向时,图像正确显示:

$file = fopen('proxy_tmp~', 'w');
fwrite($file, $content);
fclose($file);
header('Location: ' . DIR . 'proxy_tmp~');

编辑 2:我有 gzip 压缩,但是当我禁用它时我遇到了同样的问题,当我在 Notepad++ 中打开两个文件时,一个是 DOS/Windows ANSI(原始),另一个是 DOS/Windows UTF-8(脚本打开的文件)。当我在记事本中打开文件并将编码更改为 ANSI 并保存文件时,一切正常。

编辑 3:我想我在 GNU/Linux 上做了同样的事情,但没有 CURLOPT_BINARYTRANSFER 选项并且它工作正常,这是我的项目 https://github.com/jcubic/yapp .我还使用 Wamp 在 Windows 10 上对其进行了测试,并且工作正常。

最佳答案

以下是如何将文件直接发送回用户以供下载(使用您的 $content 变量):

$file_array = explode("\n\r", $content, 2);
$header_array = explode("\n", $file_array[0]);
foreach($header_array as $header_value) {
$header_pieces = explode(':', $header_value);
  if(count($header_pieces) == 2) {
    $headers[$header_pieces[0]] = trim($header_pieces[1]);
  }
}
header('Content-type: ' . $headers['Content-Type']);
header('Content-Disposition: ' . $headers['Content-Disposition']);
echo substr($file_array[1], 1);

这里有一个完整的例子:

http://ryansechrest.com/2012/07/send-and-receive-binary-files-using-php-and-curl/

关于php - 如何在 php 中显示来自 curl 的二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17520987/

相关文章:

php - MYSql ORDER BY CASE 第一个 CASE 应按 ID 数组排序

html - 将 HTML 转换为图像的简单 HTML 布局引擎

jquery - 使用 jQuery 在 ul 中定位 img 标签

php - cURL 错误 60 - SSL 证书问题 - 无法获取本地颁发者

php - 修复 SSL 证书问题 : unable to get local issuer certificate for real in PHP

php - 拉 <s :variant> from atom feed with simple pie

php - 如何在 PHP 中检测 w3.org 的机器人?

php - 如何确保对 CakePHP Controller /操作的 jQuery 自动完成调用中的路径正确解析?

node.js - 如何使用 Node js 的 ejs 模板引擎显示图像标签?

node.js - request.js 失败,而 CURL 对于带有授权 header 的 GET 请求成功