将图像拉入PHP文件

时间:2009-01-15 13:57:25

标签: php image gd

我在同一目录中有一个PHP文件和一个图像。我怎么能得到PHP文件将它的标题设置为jpeg并将图像“拉”到其中。所以,如果我去file.php,它会显示图像。如果我将file.php重写为file_created.jpg并且它需要工作。

2 个答案:

答案 0 :(得分: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会产生很大的不同。

如果你想得到可靠的,你可以输出最后修改的时间,并检查If-Modified-Since标头的传入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);

答案 1 :(得分:1)

应该很容易:

<?php
    $filepath= '/home/foobar/bar.jpg';
    header('Content-Type: image/jpeg');
    echo file_get_contents($filepath);
?>

你只需要弄清楚如何确定正确的mime类型,这应该是非常简单的。

相关问题