如何在PHP中使用curl_exec()创建具有空值的自定义HTTP头?

如何在PHP中使用curl_exec()创建具有空值的自定义HTTP头?,php,http-headers,Php,Http Headers,这个问题大致相当于此处所述的问题: 关键是有些web服务(不方便)需要发布 空HTTP头值。例如,您可能有一个RESTful API 发布需要此HTTP标头: Content-Type: text/json Content-Length: 1024 ... Custome-Header-Field: hello Required-Empty-Header-Field: ... Connection: Keep-Alive 这里的要点是必须指定必需的空标头字段,并且必须为空 如何在PHP上下文

这个问题大致相当于此处所述的问题:

关键是有些web服务(不方便)需要发布 空HTTP头值。例如,您可能有一个RESTful API 发布需要此HTTP标头:

Content-Type: text/json
Content-Length: 1024
...
Custome-Header-Field: hello
Required-Empty-Header-Field:
...
Connection: Keep-Alive
这里的要点是必须指定必需的空标头字段,并且必须为空

如何在PHP上下文中的curl_exec中实现这一点

我将回答我自己的问题,因为我花了一段时间才弄明白。
但是我很想看看其他程序员都说了些什么。

我还没有测试过这个,但是试着为这个值设置一个空格。这可能会通过cURL所做的任何验证,并且应该忽略标题中某个值之前的空格

// Assume we are POSTing data from the variable $data.
$http_header = array(
  "Content-Type: application/x-www-form-urlencoded" . "\r\n" .
  "Content-Length: ". strlen($data) . "\r\n" .
  ...
  "Custome-Header-Field: hello" . "\r\n" .
  "Required-Empty-Header-Field:" . "\r\n" .
  ...
  "Connection: Keep-Alive",
  "Other-Value-One: world",
  "Other-Value-Two: thisworks");

// Add optional headers.
if (!empty($some_condition)) {
  array_push($http_header, "Other-Value-Three: whatever");
}

// Set up curl_exec.
$curl = curl_init();
$url = "https://www.somewhere-over-the-rainbow.com";
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $httpHeader);
$response = curl_exec($curl);
curl_close($curl);