在PHP中使用curl_exec(),如何创建一个空值的自定义HTTP头


Using curl_exec() in PHP, how do you create a custom HTTP header with an empty value?

这个问题大致相当于这里解决的问题:

http://curl.haxx.se/mail/lib-2010-08/0118.html

重点是有些web服务(不方便)需要张贴空HTTP标头值。因此,例如,您可能有一个RESTful API需要此HTTP标头才能进行POST:

Content-Type: text/json
Content-Length: 1024
...
Custome-Header-Field: hello
Required-Empty-Header-Field:
...
Connection: Keep-Alive

这里的要点是必须指定必需的空标头字段,并且必须为空。

如何在PHP上下文中的curl_exec中做到这一点?

我将回答我自己的问题,因为我花了一段时间才弄清楚。但我很好奇其他程序员会怎么说。

// 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);

我还没有测试过,但试着只为值设置一个空格。这可能会通过cURL正在进行的任何验证,并且应该忽略标头中值之前的空白。