2016-07-13 87 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很高兴能帮到你。请选择我的答案作为问题的答案。 –