PhoenixTech
PhoenixTech

Reputation: 209

php - Posting Array via CURLOPT_POSTFIELDS

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?

Upvotes: -1

Views: 1179

Answers (2)

Prince Dorcis
Prince Dorcis

Reputation: 1045

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

Upvotes: 1

Игорь Тыра
Игорь Тыра

Reputation: 955

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.

Upvotes: 0

Related Questions