为什么使用file_get_contents()时会出现500错误,但在浏览器中可以正常工作?

35
$html = file_get_contents("https://www.[URL].com"); 
echo $html;

在错误日志中出现如下内容:

PHP警告:file_get_contents(https://www.[URL].com)[function.file-get-contents]:打开流失败! HTTP请求失败!HTTP/1.1 500 Internal Server Error in /Applications/MAMP/htdocs/test.php on line 13";

但是,在浏览器中该网站运行正常。

我也尝试使用cURL,虽然日志文件中没有任何错误,但$html现在输出:

'/'应用程序中的服务器错误。未将对象引用设置到对象的实例。
...一些更多的调试信息

有什么方法可以解决这个问题吗?


1
你考虑过询问托管另一个网站的人吗? - Ignacio Vazquez-Abrams
2个回答

78

尝试使用这个解决方法:

$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);
如果这行不通的话,也许你无法从https读取?

有趣的解决方案。然而,当我将用户代理更改为Chrome时,现在会出现400错误。不过使用"MyAgent"字符串就完美地解决了。 - remarsh
3
谢谢 - 它有效,但我很好奇为什么它有效。有具体的推理吗? - Dan Smart
1
@DanSmart PHP的默认用户代理(很可能只是一个空字符串)被您请求网页的Web服务器阻止了。这就是为什么您可能需要设置一个虚假的用户代理。 - Gökhan Mete ERTÜRK
原因是Web应用程序在处理用户代理标头时出现了问题。例如,他们的数据库在插入空User-Agent时出现了问题。 - Nick Tsai
@modu 有没有一种默认情况下解除阻止的方法?因为在 php.ini 中设置 allow_url_open 并不起作用,谢谢。 - Fernando Torres
@FernandoUrban 你可以尝试使用curl。 - Gökhan Mete ERTÜRK

5

我必须在头部输入更多数据:

$opts = array('http' => array(
    'method' => "GET",
    'header' => "User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0\r\n"
    . "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
    . "Accept-Encoding:gzip, deflate\r\n"
    . "Accept-Language:cs,en-us;q=0.7,en;q=0.3\r\n"
    . "Connection:keep-alive\r\n"
    . "Host:your.domain.com\r\n"
    ));
$context = stream_context_create($opts);
$html = file_get_contents($sap_url, FALSE, $context);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接