php 为什么在使用 file_get_contents() 时出现 500 错误,但在浏览器中有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10524748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:24:02  来源:igfitidea点击:

Why I'm getting 500 error when using file_get_contents(), but works in a browser?

phpfile-get-contents

提问by bdev

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

produces this in the error logs:

在错误日志中产生这个:

PHP Warning: file_get_contents(https://www.[URL].com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in /Applications/MAMP/htdocs/test.php on line 13";

PHP 警告:file_get_contents(https://www.[URL].com) [function.file-get-contents]:无法打开流:HTTP 请求失败!第 13 行 /Applications/MAMP/htdocs/test.php 中的 HTTP/1.1 500 内部服务器错误”;

However, the site works fine in a browser.

但是,该站点在浏览器中运行良好。

I tried using cURL as well. I don't get any errors in the log file, but $htmlnow echoes:

我也尝试使用 cURL。我在日志文件中没有收到任何错误,但$html现在回显:

Server Error in '/' Application.
Object reference not set to an instance of an object.

...some more debugging info

“/”应用程序中的服务器错误。
你调用的对象是空的。

...更多调试信息

Any ideas how to work around this?

任何想法如何解决这个问题?

回答by blang

Try this workaround:

试试这个解决方法:

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

If this doesn't work, maybe you cant read from https?

如果这不起作用,也许您无法从https读取?

回答by Racky

I had to enter more data into the header:

我不得不在标题中输入更多数据:

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