2011-07-18 24 views
4

我有一個PHP腳本,它從遠程服務器獲取圖像,以便我可以使用HTML5畫布API處理它。file_get_contents在生產服務器上無法正常工作,可以在本地使用

<?php 
if ((isset($_GET['url']))) { 
    $url = $_GET['url']; 
    $file_format = pathinfo($url, PATHINFO_EXTENSION); 
    try 
    { 
     header("Content-Type: image/$file_format"); 
     header("Content-disposition: filename=image.$file_format"); 
     $img = file_get_contents($url); 
     echo $img; 
    } 

    catch(Exception $e) 
    { 
     echo $e->getMessage(); 
    } 
} 

else die('Unknown request'); 
?> 

一個典型的要求是這樣的:

fetch_image.php?url=http://example.com/images/image.png 

一切正常,我的本地服務器上,但在生產服務器上給我這個錯誤:

NetworkError: 500 Internal Server Error.

的錯誤日誌寄存器這消息:

PHP Warning: Cannot modify header information - headers already sent.

我已經嘗試了一些建議,但它不工作:

allow_url_fopen = 1 
+0

請粘貼完整的腳本(包括'<?php'標籤)。 – Dogbert

+0

聽起來像一個錯誤的道路事 –

+0

錯誤指向什麼行?請同時發佈確切的錯誤信息。 – Dogbert

回答

11

檢查服務器是否允許使用文件功能打開遠程URL(php.ini「allow_url_fopen」設置必須爲「true」)。

1

嘗試

ob_start() 
在開始

ob_end_flush() 

在腳本的結尾。還要確保該腳本在<?php之前不包含任何字符。

0

開始輸出內容時會發送標題。因此,在上面提供的代碼之前,內容會被回顯(來自PHP或純HTML或JavaScript)。你需要尋找發生的地方。

1

出於安全原因,您應該確保您的託管服務提供商未禁用遠程URL提取。設置爲allow_url_fopen,您可以使用phpinfo()檢查當前配置。在這種情況下,file_get_contents()應該返回FALSE,因此您必須使用===運算符測試$img,否則將不會產生錯誤。

0
  1. 你應該檢查該文件的編碼爲UTF-8將打破頭
  2. 檢查它在運行該腳本之前,你的文件沒有打印任何其他數據。
1

嘗試這種方式從manual

<?php 
if ((isset($_GET['url']))) { 
    $url = $_GET['url']; 
    $file_format = pathinfo($url, PATHINFO_EXTENSION); 
    try 
    { 
     ob_clean(); 
     ob_start(); 

     header("Content-Type: image/$file_format"); 
     header("Content-disposition: filename=image.$file_format"); 
     $img = file_get_contents(urlencode($url)); 
     // as per manual "If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode(). " 
     echo $img; 
     echo ob_get_clean(); 
     exit(); 
    } 

    catch(Exception $e) 
    { 
     echo $e->getMessage(); 
    } 
} 

else die('Unknown request'); 
?> 

多了一個解決方案有時你可能會得到一個錯誤打開一個HTTP URL。 儘管你已經在php.ini中設置了「allow_url_fopen = On」

對我來說,解決方案也是將「user_agent」設置爲某個東西。

相關問題