我正在设置一个随机图像函数,但在处理随机发生器之前试图证明这个概念。
现在我有一个 test.php 文件。它包含了:
<?php
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');
header('Content-type: image/jpeg;');
header("Content-Length: " . filesize($img));
fpassthru($fp);
exit;
?>
Run Code Online (Sandbox Code Playgroud)
然后在另一个 html 文件中我有 <img src="test.php">
目标只是返回图像。图像 url 工作是正确的,test.php 返回 200。但图像只显示小破碎的图像图标。
我也试过readfile()没有运气。
我只是想展示这张图片。
filesize不适用于 HTTP URL。该文件说:
此函数还可与某些 URL 包装器一起使用。请参阅支持的协议和包装器以确定哪些包装器支持 stat() 系列功能。
但是,HTTP 包装器不支持该stat功能。因此,您发送了错误的Content-Length标头,并且您的浏览器无法解释 HTTP 响应。
我看到两种可能的解决方案:
将图像加载到内存中并使用strlen:
$image = file_get_contents('http://example.com/img.jpg');
header('Content-type: image/jpeg;');
header("Content-Length: " . strlen($image));
echo $image;
Run Code Online (Sandbox Code Playgroud)使用该$http_response_header变量读取远程响应的Content-Length标头:
$img = 'http://example.com/img.jpg';
$fp = fopen($img, 'rb');
header('Content-type: image/jpeg;');
foreach ($http_response_header as $h) {
if (strpos($h, 'Content-Length:') === 0) {
header($h);
break;
}
}
fpassthru($fp);
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
8001 次 |
| 最近记录: |