Jump to content

Archived

This topic is now archived and is closed to further replies.

Splash

cURL - sending array as post value

Recommended Posts

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($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

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

curl_close ($ch);

Share this post


Link to post
Share on other sites

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($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

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

curl_close ($ch);

Share this post


Link to post
Share on other sites

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:

 

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.