Send headers in HTTP Request with Curl in PHP

Asked

Viewed 1,950 times

1

Hello, I made a function to make Curl calls to an API and I’m able to make the calls but I’m 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 scanned 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?

1 answer

1


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

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

Each array value must be a row, following the header pattern (Nome: Valor). For comparison, you are 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 the array would be a foreach:

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

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

Utilize $h as an argument for the CURLOPT_HTTPHEADER.

  • I changed the array structure as seen in edited code. Even so the result is the same.

  • Are you giving the var_dump before the curl_exec, it has no way to get the correct information. Run Curl and give var_dump later and see the values of request_header or give a var_dump(curl_getinfo($ch, CURLINFO_HEADER_OUT ));, also after the exec.

  • Apparently there’s no problem.

  • You’re right, I don’t know how I could miss it. Also when I select the parameter 'CURLOPT_HEADER => true' the value returns null. But thanks for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.