Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

curl

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); 
like image 750
hakre Avatar asked Feb 28 '13 11:02

hakre


People also ask

What is Curlopt_httpheader?

Use CURLOPT_HEADEROPT to make the headers only get sent to where you intend them to get sent. Custom headers are sent in all requests done by the easy handles, which implies that if you tell libcurl to follow redirects (CURLOPT_FOLLOWLOCATION), the same set of custom headers will be sent in the subsequent request.

What is Curl_exec?

curl_exec(CurlHandle $handle ): string|bool. Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.

What is the use of Curl_setopt?

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.

What is Curlopt_postfields?

CURLOPT_POSTFIELDS. The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'.


2 Answers

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)
like image 135
hakre Avatar answered Sep 28 '22 19:09

hakre


Other type of format :

$headers[] = 'Accept: application/json'; $headers[] = 'Content-Type: application/json'; $headers[] = 'Content-length: 0';  curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers); 
like image 20
Pascual Muñoz Avatar answered Sep 28 '22 20:09

Pascual Muñoz