为什么我在使用file_get_contents()时得到500个错误,但是在浏览器中工作?

时间:2023-01-12 21:53:53
$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)[功能。文件-内容]:未打开流:HTTP请求失败!HTTP/1.1 500内部服务器错误/应用/MAMP/htdocs/测试。php在13号线”;

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 $html now echoes:

我也试过用旋度。我在日志文件中没有任何错误,但是$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?

有什么办法解决这个问题吗?

2 个解决方案

#1


69  

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读取数据?

#2


4  

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

#1


69  

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读取数据?

#2


4  

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