2014-10-09 33 views
2

此卷曲示例适用。散列是$ username的base64编码。 ':'。 $密码。适当的卷曲方式授权:基本散列

curl -H "Authorization: Basic b2ZmZXJib3NzqGdtYxlsLmNvbupHcmVtbdFuJA==" https://somedomain.com/login 

下面的PHP代码无法正常工作,并返回 “状态”: “未授权”, “的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

虽然它可能不是“正确”的方式,但通过基本身份验证,您通常可以在URL中指定用户名/密码,如“http:// username:password @ www.whatever.com/path / – 2014-10-09 18:08:26

回答

2

你是编码字符串两次。

使用CURLOPT_USERPWD时,不需要使用base64_encode,因为这是此选项的作用。

所以这应该工作:

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); 

如果你想使用base64_encode你应该添加一个名为 '授权' 的头和一起通过哈希字符串:

$hash = base64_encode($username . ":" . $password); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: Basic $hash" 
); 

参考文献:

curl_setopt

CURLOPT_USERPWD