我是新来的PHP,我使用狂饮客户做出REST调用并且还使用$_SERVER
变量添加请求头。
但在我的请求呼叫时,有时用户发送报头(x-api-key
),有时也没有报头。当请求不发送标题我的PHP狂饮抛出一个错误,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错误。
您可以单独设置页眉,检查其中的每个人都必须事先补充条件:
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;
?>```