Skip to content
Advertisement

Using an array as request headers in PHP

I’m trying to send a GET request to an API using PHP stream_context_create and file_get_contents.

I need to add API keys to the headers of my request, I’m storing these in an array so I easily edit them later and use them in multiple functions. What is a good way to include these arrays as headers?

In this case the key of the array would be the header keys and the value of the array the value of the header.

Some code to explain the problem

<?php
$api = array(
    "X-Api-Id" => "id",
    "X-Api-Key" => "key",
    "X-Api-Secret" => "secret"
);

$options = array(
    "http" => array(
        "header" => "Content-type: application/x-www-form-urlencodedrn", // here I need to add the $api array
        "method" => "GET"
    )
);  
return file_get_contents("example.com", FALSE, stream_context_create($options));
?>

Advertisement

Answer

Simply add the info to the header.

<?php
$api = [
    'X-Api-Id' => 'id',
    'X-Api-Key' => 'key',
    'X-Api-Secret' => 'secret',
];
$headerData['Content-type'] = 'application/x-www-form-urlencoded';
$headerData = array_merge($headerData, $api);
array_walk($headerData, static function(&$v, $k) { $v = $k.': '.$v; });

$options = array(
    'http' => [
        'header' => implode("n", $headerData),
        'method' => 'GET'
    ]
);  
return file_get_contents('example.com', FALSE, stream_context_create($options));
?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement