Php 如何在Rest服务器API中获取/设置标头?
我有一个Rest服务器,它像通常的API服务器一样侦听客户机请求。 根据客户端请求,我只想在头中向客户端发送/响应一些数据。Php 如何在Rest服务器API中获取/设置标头?,php,codeigniter,codeigniter-2,codeigniter-restserver,Php,Codeigniter,Codeigniter 2,Codeigniter Restserver,我有一个Rest服务器,它像通常的API服务器一样侦听客户机请求。 根据客户端请求,我只想在头中向客户端发送/响应一些数据。 我的问题是: 如何首先访问客户端头然后 如何在Rest服务器中设置标头 这是我向REST服务器发送请求的方式: function request_curl($url = NULL) { $utc = time(); $post = "id=1&CustomerId=1&amount=2450&operatorName
我的问题是:
然后
function request_curl($url = NULL) {
$utc = time();
$post = "id=1&CustomerId=1&amount=2450&operatorName=Jondoe&operator=12";
$header_data = array(
"Content-Type: application/json",
"Accept: application/json",
"X-API-KEY:3ecbcb4e62a00d2bc58080218a4376f24a8079e1",
"X-UTC:" . $utc,
);
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => 'http://domain.com/customapi/api/clientRequest',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $header_data,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => 1,
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) {
die(curl_error($ch));
}
curl_close($ch);
echo '<pre>';
print_r($answer);
echo '</pre>';
}
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
可以尝试使用php函数getallheaders(),它将为您获取所有标题数据。如果要将其转换为数组,请使用foreach 因此,这将获得标题数据并将其转换为数组
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
现在,如果您想获取body并将其转换为数组
public function clientRequest_post() {
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
$this->response($entityBody, 200);
}
最后一个函数将如下所示
顺便说一句,我假设
$this->response($entityBody,200)代码>将为您生成响应。祝您好运getallheaders并非始终可用
public function clientRequest_post() {
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
$this->response($entityBody, 200);
}