0

I've been stuck trying to debug this .. im passing a multidimensional array to another script via cURL, and i wanted to do something with that array after passing it the curl execution .. however it seems that after the array passed through curl (a copy of it at least), the original array gets messed up!

$myarray[0]['name'] = "TJ";
$myarray[0]['age'] = "21";
$myarray[0]['sex'] = "yes please";

printr($myarray); //outputs the array properly

//upload the array data as-is to central
// Get cURL resource
$curl = curl_init();
// Set some options for cURL
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://localhost/projects/sync_dtr.php?',
    CURLOPT_USERAGENT => 'TK local code: blq ',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => $myarray 
));
// Send the request & save response to $resp
$response = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

printr($myarray); //doesn't output the array properly, instead it outputs "Array ( [0] => Array ) "

is this a bug or an expected result/effect? i don't understand how cURL wrote/modified the original array. heck even if i make a copy of the $myarray , and use one copy in cURL , bot copies get messed up!!

but if i don't use multidimensional array, everything seems to be fine.

BrownChiLD
  • 3,545
  • 9
  • 43
  • 61

2 Answers2

8

What happens internally is that each top array element is turned into a string; unfortunately, this is performed without applying copy-on-write semantics. I won't go as far as calling this a bug, but it's definitely something unintuitive.

That said, CURLOPT_POSTFIELDS shouldn't be used for multi-dimensional values; instead, use http_build_query():

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
    'myarray' => $myarray
)));

Btw, I've made sure the top level element is a string; this is kind of necessary for url-encoded form values.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Why does curl unset the array anyways (which is the actual question)? The documentation does not say the variable is passed by reference. – Daniel W. Aug 18 '14 at 12:31
  • @DanFromGermany It doesn't unset it; it does a string cast on each element. – Ja͢ck Aug 18 '14 at 12:31
2

cURL can only accept a simple key-value paired array where the values are strings.
See Answer at: Post multidimensional array using CURL and get the result on server

However, I would recommend you serialize your array to JSON String. Then on the recieving end of the CURL Post, deserialize the String.

See: PHP json_encode()

and: PHP json_decode()

Community
  • 1
  • 1
Zander Rootman
  • 2,178
  • 2
  • 17
  • 29