3

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

3 Answers3

4

You also need to specify "Authorization"...

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: Bearer ".$access_token
));
fatlog
  • 1,182
  • 2
  • 14
  • 28
2

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

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

NCP
  • 81
  • 1
  • 10
2

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);
Dharman
  • 30,962
  • 25
  • 85
  • 135
shaft
  • 361
  • 3
  • 8