【问题标题】:Getting headers when streaming images through PHP from a database通过 PHP 从数据库流式传输图像时获取标题
【发布时间】:2009-11-19 17:54:22
【问题描述】:

我有一些非常简单的 php 代码,可以从数据库中返回二进制图像数据。

ob_start();

$stmt = $db->prepare($sql);
$stmt->execute(array($ImageID));
$stmt->bindColumn(1, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

ob_clean();
header("Content-Type: " . $content_type);

fpassthru($lob);

让我们将此脚本称为 get_image.php。我从另一个脚本调用这个脚本来获取图像数据然后处理它。像这样。

$src = file_get_contents('example.com/get_image.php?ImageID=foo');

$src = imagecreatefromstring($src);
imagecopyresized($newfile, $src, 0, 0, 0, 0, $newwidth, $newheight, $origwidth, $origheight);

我从图像处理函数中收到错误消息,提示“数据不是可识别的格式”。在查看响应后,我的 $src 变量看起来包含标头以及二进制数据。我一直在做研究,但我不知道如何摆脱标头输出而只使用原始二进制字符串。任何帮助表示赞赏。

要清楚,如果我打印出 $src 字符串,而不是原始二进制数据,我会得到以下内容。

HTTP/1.1 200 OK
Date: Thu, 19 Nov 2009 17:33:01 GMT
Server: Apache/2.2.8 (Unix) ...
X-Powered-By: PHP/5.2.11
Connection: close
Content-Type: image/jpeg

/* Then all the binary data */

【问题讨论】:

标签: php database streaming


【解决方案1】:

我不是 PHP 专家,这可能是真正的解决方案(仅获取响应正文,没有标头),但我知道我的 HTTP。为此,像上面这样的 HTTP 请求的标头和正文始终由两个 <CR><LF> 分隔。您应该能够接受响应,并从那里获取子字符串。示例 iDontKnowPhp 代码:

$start = $src.positionOf('<CR><LF><CR><LF>')
$stop  = $src.lenght()
$img   = $src.sub($start, $stop)

【讨论】:

  • 谢谢。这是一个简单的解决方案,而且效果很好。我首先添加了对标题的检查。 stripos($src, 'http') === 0
【解决方案2】:

看起来 PHP fopen 流包装器没有剥离标题。代替 file_get_contents 尝试 CURL:

<?php

$ch = curl_init("http://www.example.com/myimagescript.php");

curl_setopt($ch, CURLOPT_HEADER, 0);  // No headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   // grab the content of the file
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$contents= curl_exec($ch);
curl_close($ch);


?> 

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2021-08-07
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多