我可以使用 CURLOPT_HTTPHEADER 多次调用 curl_setopt 来设置多个头吗?

我可以多次调用 curl_setoptCURLOPT_HTTPHEADER来设置多个头吗?

$url = 'http://www.example.com/';


$curlHandle = curl_init($url);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Content-type: application/xml'));
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Authorization: gfhjui'));


$execResult = curl_exec($curlHandle);
176750 次浏览

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No.

No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER more than once, passing it a single header each time, in order to set multiple headers.

A second call will overwrite the headers of a previous call (e.g. of the first call).

Instead the function needs to be called once with all headers:

$headers = array(
'Content-type: application/xml',
'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

Other type of format :

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';


curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
/**
* If $header is an array of headers
* It will format and return the correct $header
* $header = [
*  'Accept' => 'application/json',
*  'Content-Type' => 'application/x-www-form-urlencoded'
* ];
*/
$header; //**
if (is_array($header)) {
$i_header = $header;
$header = [];
foreach ($i_header as $param => $value) {
$header[] = "$param: $value";
}
}