Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?
PhpCurlPhp 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:
- How to send a header using a HTTP request through a curl call? (curl on the commandline)
- How to get an option previously set with curl_setopt()? (curl PHP extension)
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";
}
}