Send headers in HTTP Request with cURL in PHP

1

Hello, I made a function to make cURL calls to an API and I am able to make the calls but I am not able to send headers.

Function:

    function curlRequest($endpoint, $verb, $headers, $params = null) {
    try {
        //Inicia o cURL
        $ch = curl_init();

        //URL da API
        $url = API_URL . $endpoint;

        if (isset($params)) {
            $fields = http_build_query($params);
        }

        //Trata o verbo
        if ($verb === 'POST' || $verb === 'PUT' || $verb === 'DELETE') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

            if ($verb == 'POST') {
                curl_setopt($ch, CURLOPT_POST, true);
            } else if ($verb == 'PUT') {
                curl_setopt($ch, CURLOPT_PUT, true);
            } else {
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            }
        }

        //CURL Options
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLINFO_HEADER_OUT => true
        ));

       //var_dump(curl_getinfo($ch));
       //var_dump($headers);
       //die();

        //Pega o retorno
        $jsonRetorno = curl_exec($ch);

        //Decodifica o JSON
        $arrayRetorno = json_decode($jsonRetorno, true);

        //Retorna o Array
        return $arrayRetorno;
    } catch (Exception $e) {
        echo 'O seguinte erro ocorreu ao fazer requisição aos servidores: ' . $e->getMessage();
    } finally {
        curl_close($ch);
    }
}

I made a vardump of the curl information and the header appears to be empty.

    /opt/lampp/htdocs/projetos/soccerama/web/application/helpers/funcoes_helper.php:41:
    array (size=26)
      'url' => string 'api.mydomain.net/usuario/autenticar' (length=39)
      'content_type' => null
      'http_code' => int 0
      'header_size' => int 0
      'request_size' => int 0
      'filetime' => int 0
      'ssl_verify_result' => int 0
      'redirect_count' => int 0
      'total_time' => float 0
      'namelookup_time' => float 0
      'connect_time' => float 0
      'pretransfer_time' => float 0
      'size_upload' => float 0
      'size_download' => float 0
      'speed_download' => float 0
      'speed_upload' => float 0
      'download_content_length' => float -1
      'upload_content_length' => float -1
      'starttransfer_time' => float 0
      'redirect_time' => float 0
      'redirect_url' => string '' (length=0)
      'primary_ip' => string '' (length=0)
      'certinfo' => 
        array (size=0)
          empty
      'primary_port' => int 0
      'local_ip' => string '' (length=0)
      'local_port' => int 0
    /opt/lampp/htdocs/projetos/soccerama/web/application/helpers/funcoes_helper.php:40:
array (size=5)
  0 => string 'Content-Type: application/json' (length=30)
  1 => string 'xAuthClienteID: 2' (length=17)
  2 => string 'xAuthChaveApi: 3851b1ae73ca0ca6e3c24a0256a80ace' (length=47)
  3 => string 'login: admin' (length=12)
  4 => string 'senha: teste' (length=12)

Am I doing something wrong? Is there another way to send the headers?

    
asked by anonymous 20.09.2017 / 15:50

1 answer

1

Possibly this occurs because the array is formatted in the wrong way. The CURLOPT_HTTPHEADER expects an array of type:

['Content-Type: application/json', 'Qualquer: Coisa'];

Each value of the array must be one line, following the pattern of the headers ( Nome: Valor ). For comparison, you're doing this an associative array between the header name and its value:

['Content-Type' => 'application/json', 'Qualquer' => 'Coisa'];

This is not supported, at least as far as I know.

A solution to convert to array would be foreach :

$arr = ['Content-Type' => 'application/json', 'Qualquer' => 'Coisa'];

$h = [];
foreach($arr as $nome => $valor){
     $h[] = $nome . ': '. $valor;
}

Use $h as argument to CURLOPT_HTTPHEADER .

    
20.09.2017 / 16:19