2009-05-22 85 views
54

我想读一个图像文件(.JPEG是精确的),和“回响”回页输出,但有是显示图像...返回一个PHP页面图像

我的index.php有这样一个图像链接:

<img src='test.php?image=1234.jpeg' /> 

和我的PHP脚本基本上做到这一点:

1)阅读1234.jpeg 2)回送文件内容... 3)我有一种感觉,我需要返回与MIME类型的输出,但这是我迷路的地方

一旦我明白了这一点,我将一起删除文件名输入,并将其替换为图像ID。

如果我不清楚,或者您需要更多信息,请回复。

+1

只需添加一些安全性,因此像``攻击可避免 – mixdev 2015-11-29 16:01:57

回答

92

PHP手册中有this example

<?php 
// open the file in a binary mode 
$name = './img/ok.png'; 
$fp = fopen($name, 'rb'); 

// send the right headers 
header("Content-Type: image/png"); 
header("Content-Length: " . filesize($name)); 

// dump the picture and stop the script 
fpassthru($fp); 
exit; 
?> 

的要点是,你必须发送一个Content-Type头。另外,在<?php ... ?>标签之前或之后,您必须小心,在文件中不要包含任何额外的空白(如换行符)。

<?php 
$name = './img/ok.png'; 
$fp = fopen($name, 'rb'); 

header("Content-Type: image/png"); 
header("Content-Length: " . filesize($name)); 

fpassthru($fp); 

你仍然需要谨慎避免在顶部空白:

正如评论所说,你可以通过省略?>标签避免多余的空白在脚本结束的危险剧本。一个特别棘手的空白形式是UTF-8 BOM。为避免这种情况,请确保将脚本保存为“ANSI”(记事本)或“ASCII”或“无签名的UTF-8”(Emacs)或类似文件。

+12

为此,一些(包括Zend公司,梨,或两者 - 我忘了),建议省略闭幕?>。它在语法上是完全有效的,并且保证了尾随空格没有问题。 – 2009-05-22 22:20:57

+10

但是,但是...它是不可思议的不关闭一个开放的:-) – 2009-05-22 22:46:13

+1

不要忽略?>。 “更容易”并不意味着“更好”。 – 2009-05-22 23:24:05

-5

另一个简单的选择(没有更好的,只是不同的),如果你不从数据库中读取只是使用一个函数来输出所有的代码... 注意:如果你也想PHP读取图像尺寸并将其提供给客户端以进行更快的渲染,您也可以使用此方法轻松完成此操作。

<?php 
    Function insertImage($fileName) { 
    echo '<img src="path/to/your/images/',$fileName,'">';  
    } 
?> 

<html> 
    <body> 
    This is my awesome website.<br> 
    <?php insertImage('1234.jpg'); ?><br> 
    Like my nice picture above? 
    </body> 
</html> 
3

这应该有效。它可能会更慢。

$img = imagecreatefromjpeg($filename); 
header("Content-Type: image/jpg"); 
imagejpeg($img); 
imagedestroy($img); 
15

readfile()通常也用于执行此任务。我不能说这是比使用fpassthru()更好的解决方案,但它对我来说效果很好,根据the docs,它不会出现任何内存问题。

这里是我对它的例子在行动:

if (file_exists("myDirectory/myImage.gif")) {//this can also be a png or jpg 

    //Set the content-type header as appropriate 
    $imageInfo = getimagesize($fileOut); 
    switch ($imageInfo[2]) { 
     case IMAGETYPE_JPEG: 
      header("Content-Type: image/jpeg"); 
      break; 
     case IMAGETYPE_GIF: 
      header("Content-Type: image/gif"); 
      break; 
     case IMAGETYPE_PNG: 
      header("Content-Type: image/png"); 
      break; 
     default: 
      break; 
    } 

    // Set the content-length header 
    header('Content-Length: ' . filesize($fileOut)); 

    // Write the image bytes to the client 
    readfile($fileOut); 

} 
0

我的工作没有内容长度。也许原因工作远程图像文件

// open the file in a binary mode 
$name = 'https://www.example.com/image_file.jpg'; 
$fp = fopen($name, 'rb'); 

// send the right headers 
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate'); 
header('Expires: January 01, 2013'); // Date in the past 
header('Pragma: no-cache'); 
header("Content-Type: image/jpg"); 
/* header("Content-Length: " . filesize($name)); */ 

// dump the picture and stop the script 
fpassthru($fp); 
exit;