简体   繁体   中英

HTTP Basic Authentication cURL using PHP

I am trying to pull in data from an API using HTTP Basic authentication. The HTTP requests to the API are protected with HTTP Basic authentication. HTTP Basic authentication consists of a token and secret.

I have tried many different techniques, but keep getting the response that authentication was not provided. I am not sure if the token:secret method is different from username:password but I cannot get this to authenticate.

stdClass Object ( [error_message] => Authentication not provided. )

Here is the API documentation - 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;
}

?>

This is wrong:

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

That's a string, not a curl constant. Try

    CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,  // authentication method

instead.

it's the difference between:

define('FOO', 'bar');

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

You need to pass your global variables into the local scope. To do this...

Change:

function get_web_page($url) {

To:

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

and change:

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

To:

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

and:

Remove the quotes around CURLAUTH_BASIC - it's a constant, not a value. (hat tip to @iainn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM