Jump to content

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);

Link to comment
https://forums.phpfreaks.com/topic/194255-curl-sending-array-as-post-value/
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);

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:

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.