401 Unauthorized response when sending a request in cURL PHP

I'm trying to get my gitlab project issues using GitLab API I've tried this but it seems not be working

<?php

$url = "https://git.exemple.com/api/v4/issues";
$ch = curl_init($url);


curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
curl_setopt($ch,CURLOPT_HTTPHEADER, 
        array(
        'Content-Type: application/json',
        'Authorization: PRIVATE-TOKEN xxxxxxxxxxxxxxxx'
    ));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$resp = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if($e = curl_error($ch)){
    echo $e;
}
else{
    $decoded = json_decode($resp,true);
    print_r($decoded);
}

curl_close($ch);

this the response I get

Array ( [message] => 401 Unauthorized )

1 answer

  • answered 2021-04-22 00:18 Skrrp

    A simple reading of the manual

    Personal/project access tokens

    suggests that your header should be:

    curl_setopt($ch,CURLOPT_HTTPHEADER, 
        array(
        'Content-Type: application/json',
        'PRIVATE-TOKEN: xxxxxxxxxxxxxxxx'
    ));
    

    or

    curl_setopt($ch,CURLOPT_HTTPHEADER, 
        array(
        'Content-Type: application/json',
        'Authorization: Bearer xxxxxxxxxxxxxxxx'
    ));