-1

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @PrinceDorcis. Particularly for the extra links. Of course, I searched existing posts before posting. Can't find everything though.
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.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.