Function http_build_query

Asked

Viewed 886 times

1

I wonder what the function is for http_build_queryin php. I read the manual, but it was vacant for me.

http_build_query

It is correct to use it within this context?

    $cURL = curl_init('http://teste');
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
    $dados = array(
            'NMCLIENTE' => $nome_lead,
            'DSEMAIL' =>  $email_lead,
            'NRTELEFONE' => $telefone_lead,
            'DSINTERESSE' => $meio_captacao,
            'DSMENSAGEM' => $mensagem
            );
    curl_setopt($cURL, CURLOPT_POST, true);

    curl_setopt($cURL, CURLOPT_POSTFIELDS,  http_build_query($dados));

    $resultado = curl_exec($cURL);
    curl_close($cURL);
  • 2

    Here are the examples in the manual.

1 answer

6


It’s nothing more than to transform your array in a format of querystring, ready to be passed to a URL. It will transform the sequence of value key and separate by a &.

It simplifies the process of:

  1. Concatenate each value key with a & (as would be done with implode());
  2. Encode the URL (as would be done with urlencode()) where all non-alphanumeric characters are replaced by a sign of % followed by two hexadecimal characters and coded spaces with a sign of +;

About using in this context you have demonstrated, it is correct but not necessary, since you inform that you will send the request through the method POST since CURLOPT_POST is true. This way you can pass on CURLOPT_POSTFIELDS both a array directly as a string URL-like.

When you pass directly the array, the Content-type of the request will automatically be of the type multipart/form-data, while if you pass a string, it will be like application/x-www-form-urlencoded.

  • Thank you very much Paulo!

Browser other questions tagged

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