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

2022-08-30 13:21:16
$html = file_get_contents("https://www.[URL].com"); 
echo $html;

在错误日志中生成以下内容:

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

但是,该网站在浏览器中工作正常。

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

“/”应用程序中的服务器错误。
对象引用未设置为对象的实例。

...更多调试信息

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


答案 1

请尝试以下解决方法:

$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读取?


答案 2

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

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

推荐