2009-01-15 71 views
0

我有一個PHP文件和一個圖像在同一個目錄中。我怎樣才能讓PHP文件將它的標頭設置爲jpeg並將圖像「拉」到它。所以如果我去了file.php它會顯示圖像。如果我將file.php重寫爲file_created.jpg並且它需要工作。將IMG拉入PHP文件

回答

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

應該很容易爲:

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

你只需要弄清楚如何確定正確的MIME類型,這應該是非常容易的。

+0

「readfile($ filepath);」甚至更短 – 2009-01-15 14:10:35