我在同一目录中有一个 PHP 文件和一个图像。我怎样才能让 PHP 文件将其标题设置为 jpeg 并将图像“拉”到其中。所以如果我去 file.php 它会显示图像。如果我将 file.php 重写为 file_created.jpg 并且它需要工作。
zuk1
问问题
501 次
2 回答
7
与其按照另一个答案的建议使用file_get_contents ,不如使用readfile并输出更多 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 头中的If-Modified-Since头,并返回一个空的 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);
于 2009-01-15T14:15:49.687 回答
1
应该很容易:
<?php
$filepath= '/home/foobar/bar.jpg';
header('Content-Type: image/jpeg');
echo file_get_contents($filepath);
?>
您只需要弄清楚如何确定正确的 mime 类型,这应该很简单。
于 2009-01-15T14:06:56.240 回答