Author Topic: cURL - sending array as post value  (Read 3511 times)

0 Members and 1 Guest are viewing this topic.

Offline SplashTopic starter

  • Irregular
  • Posts: 21
  • Gender: Male
    • View Profile
cURL - sending array as post value
« on: March 05, 2010, 10:00:30 AM »
Hi all,

I'm trying to send some data to a remote domain but am having an issue with one of the variables being an array. The problem is that the preferences array loses it's individual values at the other end. Any idea what I'm doing wrong here?

 

$url 
'http://foo.com/';

 
	
$params = array(
 
	
	
'name' => ' Test',
                
'age' =>  24,
                
'preferences' => array(1,2,3,4,5,6)
 
	
)
 
    
$user_agent "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    
$ch curl_init();
    
curl_setopt($chCURLOPT_POST,1);
    
curl_setopt($chCURLOPT_POSTFIELDS,$params);
    
curl_setopt($chCURLOPT_URL,$url);
    
curl_setopt($chCURLOPT_USERAGENT$user_agent);
    
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
	

	
if(
curl_exec($ch) === false) {
	
	
echo 
0;
	
} else {
	
	
echo 
1;
	
}
	

	
curl_close ($ch);


Offline SplashTopic starter

  • Irregular
  • Posts: 21
  • Gender: Male
    • View Profile
Re: cURL - sending array as post value
« Reply #1 on: March 05, 2010, 10:12:55 AM »
Figured this out. Needed to do it as a string. e.g.


$url 
'http://foo.com/';

$params 'name=test&age=24&preferences[]=1&preferences[]=2&preferences[]=3&preferences[]=4&preferences[]=5&preferences[]=6';
 
    
$user_agent "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    
$ch curl_init();
    
curl_setopt($chCURLOPT_POST,1);
    
curl_setopt($chCURLOPT_POSTFIELDS,$params);
    
curl_setopt($chCURLOPT_URL,$url);
    
curl_setopt($chCURLOPT_USERAGENT$user_agent);
    
curl_setopt($chCURLOPT_RETURNTRANSFER,1);

if(
curl_exec($ch) === false) {
  echo 
0;
} else {
  echo 
1;
}

curl_close ($ch);

Offline salathe

  • Lazy
  • Administrator
  • Addict
  • *
  • Posts: 1,540
  • Gender: Male
  • Temperament: Snuggly
    • View Profile
    • My Blog
Re: cURL - sending array as post value
« Reply #2 on: March 05, 2010, 10:19:37 AM »
For what it's worth, you can (likely) use the http_build_query() function to make an array into the required string format.

$example = array('a' => 'apple''b' => 'banana');
$postfields http_build_query($example);
echo 
$postfields;


Gives us the array formatted as a=apple&b=banana :shy:
PHP Documentation — Read it, or the badger will come for you.
http://php.net/manual/