[英]PHP file_get_contents “authorization required”
I'm trying to fetch a file from a server that requires authentication. 我正在尝试从需要身份验证的服务器中获取文件。 I have the following PHP code:
我有以下PHP代码:
//Import categories
$url = "http://$username:$password@www.example.com";
$categoriesXML = file_get_contents($url);
var_dump($url . " > " . $categoriesXML);
return;
The output of this page is merely: string(22) "Authorization Required". 该页面的输出仅是:string(22)“需要授权”。 I also tried with:
我也尝试过:
$context = stream_context_create(array('http' => array('header' => "Authorization: Basic " . base64_encode("$username:$password"))));
$url = "http://www.example.com";
$categoriesXML = file_get_contents($url, false, $context);
var_dump($categoriesXML);
return;
I tried with cURL as well with the following code: 我也尝试使用cURL和以下代码:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
var_dump($output);
return;
The cURL returns a 301 code in the $info and the $output is empty. cURL在$ info中返回301代码,而$ output为空。 I'm a PHP/server newbie, what am I doing wrong?
我是PHP /服务器新手,我在做什么错?
The OP's problem was due to choosing the wrong HTTP auth mechanism. OP的问题是由于选择了错误的HTTP身份验证机制造成的。 Setting
CURLOPT_AUTH
to CURLAUTH_BASIC
or the more permissive CURLAUTH_ANY
proved to solve the problem. 事实证明,将
CURLOPT_AUTH
为CURLAUTH_BASIC
或更宽松的CURLAUTH_ANY
可以解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.