I'm having problems posting an array using PHP cURL. I have successfully posted other values to the same page using POST-variables. But this one is hard to figure out. The only problem is how I should present the data to the server.
I checked the original form using a form analyzer. And the form analyzer shows that the POST variables are sent like this:
array fundDistribution' =>
array
204891 => '20' (length=2)
354290 => '20' (length=2)
776401 => '20' (length=2)
834788 => '40' (length=2)
The values are just for showing an example. But they will be the same length.
My problem is that the responding server does not recognise the values when I send them like this:
Array(
[104786] => 20
[354290] => 20
[865063] => 20
[204891] => 20
[834788] => 20)
My question is: How do I send the data so the server understands it?
Thank you!
You need to set post to true. Then you can pass the associative array in the POSTFIELDS option. as shown below.
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $your_array);
function flatten_GP_array(array $var,$prefix = false){
$return = array();
foreach($var as $idx => $value){
if(is_scalar($value)){
if($prefix){
$return[$prefix.'['.$idx.']'] = $value;
} else {
$return[$idx] = $value;
}
} else {
$return = array_merge($return,flatten_GP_array($value,$prefix ? $prefix.'['.$idx.']' : $idx));
}
}
return $return;
}
//...
curl_setopt($ch, CURLOPT_POSTFIELDS,flatten_GP_array($array));
Try this:
function postVars($vars,$sep='&') { $str = ''; foreach( $vars as $k => $v) { if(is_array($v)) { foreach($v as $vk=>$vi) { $str .= urlencode($k).'['.$vk.']'.'='.urlencode($vi).$sep; } } else { $str .= urlencode($k).'='.urlencode($v).$sep; } } return substr($str, 0, -1); }
As the Sepehr Lajevardi says, You should use:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($your_array));