Posting multidimensional array with PHP and CURL Posting multidimensional array with PHP and CURL arrays arrays

Posting multidimensional array with PHP and CURL


function http_build_query_for_curl( $arrays, &$new = array(), $prefix = null ) {    if ( is_object( $arrays ) ) {        $arrays = get_object_vars( $arrays );    }    foreach ( $arrays AS $key => $value ) {        $k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key;        if ( is_array( $value ) OR is_object( $value )  ) {            http_build_query_for_curl( $value, $new, $k );        } else {            $new[$k] = $value;        }    }}$arrays = array(    'name' => array(        'first' => array(            'Natali', 'Yura'        )    ));http_build_query_for_curl( $arrays, $post );print_r($post);


The concept of an array doesn't really exist when it comes to HTTP requests. PHP (and likely other server-side languages) has logic baked in that can take request data that looks like an array (to it) and puts it together as an array while populating $_GET, $_POST etc.

For instance, when you POST an array from a form, the form elements often look something like this:

<form ...>  <input name="my_array[0]">  <input name="my_array[1]">  <input name="my_array[2]"></form>

or even:

<form ...>  <input name="my_array[]">  <input name="my_array[]">  <input name="my_array[]"></form>

While PHP knows what to do with this data when it receives it (ie. build an array), to HTML and HTTP, you have three unrelated inputs that just happen to have similar (or the same, although this isn't technically valid HTML) names.

To do the reverse for your cURL request, you need to decompose your array into string representations of the keys. So with your name array, you could do something like:

foreach ($post['name'] as $id => $name){  $post['name[' . $id . ']'] = $name;}unset($post['name']);

Which would result in your $post array looking like:

Array(    [name[0]] => Jason    [name[1]] => Mary    [name[2]] => Lucy    [id] => 12    [status] => local    [file] => @/test.txt)

And then each key in the array you are posting would be a scalar value, which cURL is expecting, and the array would be represented as you need to for HTTP.


You'd have to build the POST string manually, rather than passing the entire array in. You can then override curl's auto-chose content header with:

curl_setopt($c, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));

Serializing/json-ifying would be easier, but as you say, you have no control over the receiving end, so you've got a bit of extra work to do.