此卷曲示例有效。哈希是$ username的base64编码。 ':' 。 $密码。
curl -H "Authorization: Basic b2ZmZXJib3NzqGdtYxlsLmNvbupHcmVtbdFuJA==" https://somedomain.com/login
以下PHP代码不起作用并返回" status" :" UNAUTHORIZED"," typeName" :" badCredentials"," typeCode" :[401,0]
$hash = base64_encode($username . ":" . $password);
echo '<p>' . $hash . '</p>'; //hash works correct
$URL='https://somedomain.com/login';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $hash);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
$result=curl_exec ($ch);
curl_close ($ch);
答案 0 :(得分:3)
您正在对字符串进行两次编码。
使用base64_encode
时无需使用CURLOPT_USERPWD
,因为这是此选项的作用。
所以这应该有效:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
如果你想使用base64_encode
,你应该添加一个名为'Authorization'的标题并将哈希字符串传递到一起:
$hash = base64_encode($username . ":" . $password);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Basic $hash"
);
参考: