Search code examples
phpcurlmultidimensional-arrayhttp-postarray-push

(PHP) $_POST + cURL + multi array


I try to send a multi array via cURL but I can't find a nice way to do it.

My code example:

$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' );

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

This will work and give the result I want on the curl_init() site:

print_r( $_POST ) :

Array (

    [a] => testa
    [b] => testb
    [c] => Array (

            [d] => test1
            [e] => test2
    )
)

I'd like to add the c array dynamically like:

$c['d'] = 'test1';
$c['e'] = 'test2';

But if I try to add an array with array_push or [] I always get and (string)Array in the Array without data.

Can anyone help me to do it?

The whole code for faster testing:

$url = 'url_to_test.php';
$data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' );
$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$buffer = curl_exec ($ch);
curl_close ($ch);

echo $buffer;

The test.php

print_r($_POST);

Thanks for any help!

cheers


Solution

  • In

    $data = array( 'a' => 'testa', 'b' => 'testb', 'c[d]' => 'test1', 'c[e]' => 'test2' )
    

    You've simply added new string keys "c[d]" and "c[e]".

    If you want a nested array, use:

    $data = array( 'a' => 'testa', 'b' => 'testb', 'c' => 
        array( 'd' => 'test1', 'e' => 'test2' )
    )
    

    -- EDIT --

    You're trying to set POST data, which is essentially a set of key value pairs. You can't provide a nested array. You could, however, serialize the nested array and decode it at the other end. Eg:

    $post_data = array('data' => serialize($data));
    

    And at the receiving end:

    $data = unserialize($_POST['data']);