2009-05-22 90 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;