简体   繁体   中英

500 internal server error file_get_contents

If I try and read a sites' source I sometimes get the following (example URL shown):

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

Yet the URL on its own is fine.. why would this happen?

I tried the following workaround suggestion but same result:

$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);

This is baffling me now...

The problem is in your User-Agent header. This worked for me:

$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);

I don't know the exact reason but while working with some servers, file_get_contents fails. But you have an alternative;

$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM