我是PHP新手,我正在使用Guzzle客户端进行Rest Call,还使用$_SERVER
变量添加了请求标头。
但是在我的请求调用中,有时用户发送Header(x-api-key
),有时没有头。当未在请求中发送标头时,我的PHP Guzzle抛出错误,
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;
?>
如何使此x-api-key
头文件为可选标题,而不触发PHP错误。
答案 0 :(得分:0)
您可以单独设置标题,检查要事先添加每个标题的条件:
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;
?>```