0

I do a lot of posting via PHP CURL. Generally, we post to servers that are expecting straight HTTP POST or JSON. So, we build the parameters as an array... and then json_encode the array or http_build_query the array... and post the result in CURLOPT_POSTFIELDS. Someone programmed some web pages for us... and they posted the form data via a secondary page by posting the array $_POST to our server... and it worked! Sure, enough I looked up the specs for CURLOPT_POSTFIELDS... and it can take a string or an array. So, I am confused... why does it seem the protocol is to convert the array to a string with http_build_query, when one can simply post the array (at least if it is one-dimensional)? Is this only because of URL encoding side-benefit of http_build_query.... or is there another reason?

P.S. When the array contained a parameter that was a complete URL, i.e. with query, such as http://example.com?a=1&b=2&c=3 the server read the data fine, even though the parameter was not URL encoded... or does posting an array automatically urlencode the elements of the array?

PhoenixTech
  • 161
  • 1
  • 7

2 Answers2

1

The type of value you pass to CURLOPT_POSTFIELDS affects the Content-type of your request. If CURLOPT_POSTFIELDS is an array, the content-type of your request will be multipart/form-data.

If CURLOPT_POSTFIELDS is a string application/x-www-form-urlencoded.

Now what happened (from your question) is, PHP is able to detect your POST parameters no matter the content-type. So both ways of sending the request will pass.

You can also take a look at this question to know which is better for which situation. Another link

Prince Dorcis
  • 955
  • 7
  • 7
  • Thanks, @PrinceDorcis. Particularly for the extra links. Of course, I searched existing posts before posting. Can't find everything though. – PhoenixTech Aug 12 '20 at 06:21
0

transfering any data over http(s) is transfering strings, it is a text transfer protocol, even if you do not explicitly convert array into string (by json_encode() or http_build_query() ) cURL will do it for you.

  • If so, what is the answer to my question? What is the purpose of http_build_query()... and why is the accepted protocol to use it? – PhoenixTech Aug 07 '20 at 22:54
  • the purpose of ```http_build_query``` is to serialize array data (into ```application/x-www-form-urlencoded``` encoding) for transferring over text transfer protocol. and then on other side the data is automaticly deserialized into array. – Игорь Тыра Aug 08 '20 at 11:07