John Seen
John Seen

Reputation: 731

Set an Optional Header in PHP Guzzle Client

I am new to PHP, I am using Guzzle client to make a Rest Call and also adding request header using $_SERVER variable.

But in my request call, sometimes the user sends a Header(x-api-key) and sometimes there is no header. When a header is not sent in request my PHP Guzzle throws an error, Notice: Undefined index: HTTP_X_API_KEY in Z:\xampp\htdocs\bb\index.php on line 16

<?php 
require './vendor/autoload.php';
$client = new \GuzzleHttp\Client();

$res = $client->request('GET', 'http://s.com',[
    'headers' => [
        'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
        'x-api-key' => $_SERVER['HTTP_X_API_KEY']   
    ]
]);

$json = $res->getBody();   

echo $json;
$manage = json_decode($json, true);
echo $manage;
?>

How can I make this x-api-key header optional and not triggering the PHP error.

Upvotes: 0

Views: 2811

Answers (1)

user3647971
user3647971

Reputation: 1056

You can set the headers individually, checking conditions in which each of them are to be added beforehand:

require './vendor/autoload.php';
$client = new \GuzzleHttp\Client();
$headers = array();
$headers['User-Agent'] = $_SERVER['HTTP_USER_AGENT'];
if(isset($_SERVER['HTTP_X_API_KEY'])){
    $headers['x-api-key'] = $_SERVER['HTTP_X_API_KEY']; // only add the header if it exists
}

$res = $client->request('GET', 'http://s.com',[
    'headers' => $headers
]);

$json = $res->getBody();   

echo $json;
$manage = json_decode($json, true);
echo $manage;
?>```

Upvotes: 1

Related Questions