Home > OS >  Passing X-Api-Key through file_get_contents
Passing X-Api-Key through file_get_contents

Time:10-01

I am trying to get data from a JSON endpoint on my streaming server. I've read that i need to pass an API key through the X-API-Key header. But not sure how to do this.

$url = file_get_contents('XXXXX/history');
$data1 = json_decode($url,true);
var_dump($data1);

this code works for me when getting json data from files that dont require the api key. How ever this now returns NULL as the key isn't being submitted through.

Any ideas?

CodePudding user response:

try this:

$url = 'XXXXX/history';
$options = array('http' => array(
    'method'  => 'GET',
    'header' => 'Authorization: Bearer '.$yourApiKey
));
$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

CodePudding user response:

try with CURL:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, 'XXXXX/history');
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3000); // 3 sec.
curl_setopt($ch, CURLOPT_TIMEOUT, 10000); // 10 sec.
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: ' . $yourApiKey
                ));
$result = curl_exec($ch);
curl_close($ch);


print_r($result);
  • Related