90

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);
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Why would you call a function multiple times when you can do this only once and get the same result? You're justing giving more overhead and you might mud the code with header declarations all over the place. – Tudor May 14 '14 at 06:44
  • 5
    It could have be useful to set some parameters conditionnally or if you create a default curl handle in a procedure and add specific headers later. – Florian F Apr 16 '18 at 19:30

3 Answers3

141

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 curl_setopt(PHP) 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 = [
    'Content-type: application/xml',
    'Authorization: gfhjui',
];
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

hakre
  • 193,403
  • 52
  • 435
  • 836
17

Other type of format :

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

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
user4603841
  • 1,246
  • 9
  • 8
Pascual Muñoz
  • 189
  • 1
  • 5
0
/**
 * 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";
    }
}
hakre
  • 193,403
  • 52
  • 435
  • 836
Tesla
  • 169
  • 1
  • 6