92

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); 
2
  • 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. Commented May 14, 2014 at 6:44
  • 6
    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. Commented Apr 16, 2018 at 19:30

3 Answers 3

148

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:

Sign up to request clarification or add additional context in comments.

Comments

21

Other type of format :

$headers[] = 'Accept: application/json'; $headers[] = 'Content-Type: application/json'; $headers[] = 'Content-length: 0'; curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers); 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.