将IMG拉入PHP文件

zuk*_*uk1 0 php gd image

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

Pau*_*xon 7

而不是使用另一个答案所建议的file_get_contents,使用readfile并输出更多的HTTP标头以便很好地播放:

   <?php
    $filepath= '/home/foobar/bar.gif'
    header('Content-Type: image/gif');
    header('Content-Length: ' . filesize($filepath));
    readfile($file);
   ?>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)