0

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.

John Seen
  • 701
  • 4
  • 15
  • 31
  • check with isset($_SERVER['HTTP_X_API_KEY']) – abestrad Feb 09 '19 at 19:03
  • `isset` works fine when no header is passed. When I am passing the header, it is sending header value as `1` to backend server. – John Seen Feb 09 '19 at 19:08
  • Use ternary operator inline if you will, `'x-api-key' => isset($_SERVER['HTTP_X_API_KEY']) ? $_SERVER['HTTP_X_API_KEY'] : 'value when no key provided'` – user3647971 Feb 09 '19 at 20:07
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Mike Doe Feb 09 '19 at 21:21

1 Answers1

1

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;
?>```
user3647971
  • 1,069
  • 1
  • 6
  • 13