简体   繁体   中英

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

This question is roughly equivalent to the issue addressed here:

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

The point is that some web services (inconveniently) require POSTing empty HTTP header values. So, for example, you may have a RESTful API that requires this HTTP header for a POST:

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

The point here is that Required-Empty-Header-Field must be specified, and must be empty.

How do you do this in curl_exec within a PHP context?

I am going to answer my own question, as this took me a while to figure out. But I'm curious to see what other programmers have to say.

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

I haven't tested this, but try just setting a blank space for the value. This may get past any validation cURL is doing, and whitespace prior to a value in the headers is supposed to be ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM