简体   繁体   中英

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

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

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl" ) answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER . The second call will overwrite the headers 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'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM