Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

PhpCurl

Php Problem Overview


Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

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

Php Solutions


Solution 1 - Php

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:

Solution 2 - Php

Other type of format :

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

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Solution 3 - Php

/**
 * 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";
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhakreView Question on Stackoverflow
Solution 1 - PhphakreView Answer on Stackoverflow
Solution 2 - PhpPascual MuñozView Answer on Stackoverflow
Solution 3 - PhpTeslaView Answer on Stackoverflow