2016-07-13 88 views
1

我正在嘗試使用HTTP基本認證從API中獲取數據。對HTTP的HTTP請求受到HTTP基本身份驗證的保護。 HTTP基本認證由一個令牌和祕密組成。使用PHP的HTTP基本認證cURL

我已經嘗試了許多不同的技術,但不斷收到未提供身份驗證的響應。我不確定令牌:祕密方法是否與用戶名:密碼不同,但我無法獲得此身份驗證。

stdClass的物體(未提供 [ERROR_MESSAGE] =>認證 。)

這裏是API文檔 - https://www.whatconverts.com/api/

<?php 


$token = "xxx"; 
$secret = "yyy"; 
$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads"); 
$resArr = array(); 
$resArr = json_decode($response); 
echo "<pre>"; print_r($resArr); echo "</pre>"; 

function get_web_page($url) { 
    $options = array(
     CURLOPT_RETURNTRANSFER => true, // return web page 
     CURLOPT_HEADER   => false, // don't return headers 
     CURLOPT_FOLLOWLOCATION => true, // follow redirects 
     CURLOPT_MAXREDIRS  => 10,  // stop after 10 redirects 
     CURLOPT_ENCODING  => "",  // handle compressed 
     CURLOPT_USERAGENT  => "test", // name of client 
     CURLOPT_AUTOREFERER => true, // set referrer on redirect 
     CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect 
     CURLOPT_TIMEOUT  => 120, // time-out on response 
     CURLOPT_HTTPAUTH  => "CURLAUTH_BASIC", // authentication method 
     CURLOPT_USERPWD  => "$token:$secret", // authentication 

    ); 


    $ch = curl_init($url); 
    curl_setopt_array($ch, $options); 

    $content = curl_exec($ch); 

    curl_close($ch); 

    return $content; 
} 

?> 
+0

您是否嘗試過單獨使用CURLOPT_USERNAME和CURLOPT_PASSWORD? –

+1

感謝您的憑據......可能希望立即讓這些更改/失效。 –

+1

刪除'CURLAUTH_BASIC'周圍的引號 - 這是一個常數,而不是一個值。 – iainn

回答

3

這是錯誤的:

CURLOPT_HTTPAUTH  => "CURLAUTH_BASIC", // authentication method 
           ^^^^^^^^^^^^^^^^ 

這就是一個字符串,而不是一個捲曲常量。嘗試

CURLOPT_HTTPAUTH  => CURLAUTH_BASIC, // authentication method 

改爲。

它的區別是:你需要你的全局變量傳遞到本地範圍

define('FOO', 'bar'); 

echo FOO // outputs bar 
echo "FOO" // outputs FOO 
0

。要做到這一點...

變化:

function get_web_page($url) { 

要:

function get_web_page($url, $token, $secret) { 

和變化:

$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads"); 

要:

$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads", $token, $secret); 

和:

刪除CURLAUTH_BASIC周圍的引號 - 它是一個常量,而不是一個值。 (hat tips to @iainn)

+0

謝謝Ben!那樣做了。 – user2748363

+0

@ user2748363很高興能幫到你。請選擇我的答案作爲問題的答案。 –