GitHub API returning message requires authentication even though I am providing access token

Viewed 3290

I am calling GitHub API https://api.github.com/user/emails from a PHP script. Basically I need GitHub email address of GitHub account used for logging in.

Here is the response I am receiving from API:

{ 
    "message": "Requires authentication", 
    "documentation_url": "https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user"
}

Even though I am passing access token with header for authorization, I am still receiving requires authentication message.

Here is my code:

    $token = $_GET['token'];
    echo $token;

    $url = "https://api.github.com/user/emails";
    $auth = "Authorization: token ".$token;
    echo $auth;
    $accept = "Accept: application/vnd.github.v3+json";
    $useragent = "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 YaBrowser/16.3.0.7146 Yowser/2.5 Safari/537.36";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($accept));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($useragent));

    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

    $res = curl_exec($ch);
    echo ($res); 
    curl_close($ch);

Any idea what I am doing wrong here? I am open to any other suggestions for getting GitHub email address associated with logged in GitHub account.

1 Answers

Calling curl_setopt() multiple times for CURLOPT_HTTPHEADER won't work because it will overwrite the previous value specified for the CURLOPT_HTTPHEADER field.

You can check this yourself by enabling CURLOPT_VERBOSE, after which you can see what cURL does internally for your request.

You'll have to specify a single array which you supply to CURLOPT_HTTPHEADER:

$headers = array(
    "Authorization: token ".$token,
    "Accept: application/vnd.github.v3+json",
    "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 YaBrowser/16.3.0.7146 Yowser/2.5 Safari/537.36"
);

Now you can just use curl_setopt() to set CURLOPT_HTTPHEADER to include all the headers specified in $headers:

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Related