2014-10-09 61 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