2012-08-12 183 views
2

如果我嘗試和閱讀網站的源我有時會收到如下(如圖所示例如URL):500內部服務器錯誤的file_get_contents

Warning: file_get_contents(http://www.iwantoneofthose.com/gift-novelty/golf-ball-finding-glasses/10602617.html) 
[function.file-get-contents]: failed to open stream: HTTP request failed! 
HTTP/1.1 500 Internal Server Error in /home/public_html/pages/scrape.html on line 165 

然而自身的URL是好的。爲什麼會出現這種情況?

我嘗試以下解決方法建議,但結果相同:

$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n")); 
$context = stream_context_create($opts); 
$header = file_get_contents('https://www.example.com',false,$context); 

現在這是莫名其妙我...

+0

[需要HTTP 500響應體文件\ _get \ _contents(PHP)](https://stackoverflow.com/questions/6040978/need-response-body-of-http-500的可能的複製-with-file-get-contents-php) – halfer 2017-07-31 13:42:06

回答

2

的問題是在你的User-Agent頭。這爲我工作:

$opts = array('http'=>array('header' => "User-Agent:Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1\r\n")); 
$context = stream_context_create($opts); 
$header = file_get_contents('http://www.iwantoneofthose.com/gift-novelty/golf-ball-finding-glasses/10602617.html',false,$context); 
+0

即使這個工作,這當然不應該如何使用用戶代理。這是多合法? – user2019515 2013-08-21 08:52:01

2

我不知道確切的原因,但也有一些服務器的工作時,file_get_contents失敗。但你有另一種選擇;

$fp = fsockopen("www.iwantoneofthose.com", 80, $errn, $errs); 
$out = "GET /gift-novelty/golf-ball-finding-glasses/10602617.html HTTP/1.1\r\n"; 
$out .= "Host: www.iwantoneofthose.com\r\n"; 
$out .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0\r\n"; 
$out .= "Connection: close\r\n"; 
$out .= "\r\n"; 
fwrite($fp, $out); 

$response = ""; 
while ($line = fread($fp, 4096)) { 
    $response .= $line; 
} 
fclose($fp); 


$response_body = substr($response, strpos($response, "\r\n\r\n") + 4); 
// or 
list($response_headers, $response_body) = explode("\r\n\r\n", $response, 2); 

print $response_body; 
+0

'print'之前的行是什麼? ('SUBSTR($ RESP ...') – user2019515 2013-08-21 09:06:08