我的API在.env文件中有AUTH_KEY。我想通过中间件检查这个KEY。 我使用cURL将所有请求发送到API(另一个域)。我无法理解如何在每次请求时发送此密钥。
特别是,我该怎么检查它。我发现了一些发送方式:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'AUTH_KEY: secret'
));
我不知道工作与否,因为我不了解如何访问此变量?
UPD。它是我自己的API)现在有说明如何发送它)
这是我的Request.php
class Request
{
//Return Array of objects with parameters 'id', 'name'
public static function sendRequest($request_type, $url, $param = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "backend_service.com/api/$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'AUTH_KEY: secret'
));
switch ($request_type) {
case "GET":
$server_output = json_decode(curl_exec($ch));
break;
case "POST":
$query = http_build_query(array(
"name" => $param->name,
"description" => $param->description,
"category_id" => 2,
"type_id" => 3)
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$server_output = curl_exec($ch);
break;
case "PUT":
$query = http_build_query(array(
"name" => $param->name,
"description" => $param->description,
"category_id" => $param->category_id,
"type_id" => $param->type_id)
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$server_output = curl_exec($ch);
break;
case "DELETE":
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_type);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
$server_output = curl_exec($ch);
break;
}
curl_close($ch);
return $server_output;
}
}
答案 0 :(得分:1)
在API端尝试以下操作:
<?php
$auth = isset(getallheaders()['AUTH_KEY']) ? getallheaders()['AUTH_KEY'] : '';
var_dump($auth);
它将为您提供标头参数AUTH_KEY
。了解更多信息getallheaders()