Sreejith Kenchath
Sreejith Kenchath

Reputation: 31

php how to use bearer token in curl get request header?

below is a working c# get request

public HttpResponseMessage ExecuteEndPoint(string endpoint,string accessTocken) {
            HttpResponseMessage responseMessage = new HttpResponseMessage();
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessTocken);
                responseMessage = client.GetAsync(endpoint).Result;
            }
            return responseMessage;
        }

I would like to do the same request in php using curl, below is what i have tried

$request_headers=array();
     $request_headers[]='Bearer: '.$access_token;
    //$request_headers[]='Content-Length:150';
    $handle1=curl_init();
    $api_url='here my api get url';


    curl_setopt_array(
        $handle1,
        array(
                CURLOPT_URL=>$api_url,
                CURLOPT_POST=>false,
                CURLOPT_RETURNTRANSFER=>true,
                CURLOPT_HTTPHEADER=>$request_headers,
                CURLOPT_SSL_VERIFYPEER=>false,
                CURLOPT_HEADER=>true,
                CURLOPT_TIMEOUT=>-1
        )
    );

    $data=curl_exec($handle1);
    echo serialize($data);

Looks like the api is not receiving access_token. Any help is appreciated. Thanks

Upvotes: 3

Views: 19442

Answers (3)

shaft
shaft

Reputation: 380

From PHP 7 you have to use those options :

$curl = curl_init();

$options = [
    CURLOPT_URL => $url,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_HTTPAUTH => CURLAUTH_BEARER,
    CURLOPT_XOAUTH2_BEARER => $token,
];

curl_setopt_array($curl, $options);
curl_exec($curl);

Upvotes: 3

NCP
NCP

Reputation: 81

$request_headers[] = 'Bearer: ' . $access_token;, it seems like a typo ->

$request_headers[] = 'Authorization: Bearer ' . $access_token; -> correct one

Upvotes: 2

fatlog
fatlog

Reputation: 1192

You also need to specify "Authorization"...

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: Bearer ".$access_token
));

Upvotes: 4

Related Questions