【发布时间】:2010-10-01 14:26:25
【问题描述】:
我在同一目录中有一个 PHP 文件和一个图像。我怎样才能让 PHP 文件将其标题设置为 jpeg 并将图像“拉”到其中。所以如果我去 file.php 它会显示图像。如果我将 file.php 重写为 file_created.jpg 并且它需要工作。
【问题讨论】:
我在同一目录中有一个 PHP 文件和一个图像。我怎样才能让 PHP 文件将其标题设置为 jpeg 并将图像“拉”到其中。所以如果我去 file.php 它会显示图像。如果我将 file.php 重写为 file_created.jpg 并且它需要工作。
【问题讨论】:
不要像另一个答案所建议的那样使用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);
【讨论】:
应该很简单:
<?php
$filepath= '/home/foobar/bar.jpg';
header('Content-Type: image/jpeg');
echo file_get_contents($filepath);
?>
您只需要弄清楚如何确定正确的 mime 类型,这应该很简单。
【讨论】: