题
我在同一目录中有一个 PHP 文件和一个图像。我怎样才能让 PHP 文件将其标头设置为 jpeg 并将图像“拉”到其中。所以如果我去 file.php 它会显示图像。如果我将 file.php 重写为 file_created.jpg 并且它需要工作。
解决方案
而不是使用 文件获取内容 正如另一个答案所建议的,使用 读文件 并输出更多 HTTP 标头以更好地发挥作用:
<?php
$filepath= '/home/foobar/bar.gif'
header('Content-Type: image/gif');
header('Content-Length: ' . filesize($filepath));
readfile($file);
?>
readfile 从文件中读取数据并直接写入输出缓冲区,而 file_get_contents 会首先将整个文件拉入内存,然后将其输出。如果文件很大,使用 readfile 会有很大的不同。
如果你想变得更可爱,你可以输出最后修改时间,并检查传入的 http 标头中的 如果-修改-自 标头,并返回一个空的 304 响应,告诉浏览器它们已经拥有当前版本......这是一个更完整的示例,展示了如何做到这一点:
$filepath= '/home/foobar/bar.gif'
$mtime=filemtime($filepath);
$headers = apache_request_headers();
if (isset($headers['If-Modified-Since']) &&
(strtotime($headers['If-Modified-Since']) >= $mtime))
{
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
exit;
}
header('Content-Type:image/gif');
header('Content-Length: '.filesize($filepath));
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT');
readfile($filepath);
其他提示
应该很容易为:
<?php
$filepath= '/home/foobar/bar.jpg';
header('Content-Type: image/jpeg');
echo file_get_contents($filepath);
?>
您只需要弄清楚如何确定正确的MIME类型,它应该是相当琐碎。
不隶属于 StackOverflow