kavita
kavita

Reputation: 45

how to send and receive data in curl

I used the following to send and receive data as following

<?php
$host="localhost";
$username="root";
$password="";
$db_name="test";

mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select db");
$query="select * from phone_gap";
$query=  mysql_query($query);
while ($row = mysql_fetch_assoc($query)) {
 $fields[]=$row;   
}

$data['details']=$fields;

$last_name="chaudhary";
$first_name="dharmendra";
//set POST variables
$url = 'http://localhost/test/get-post.php';
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

?>

and the get-post.php

foreach ($data['details'] as $key => $value) {
    print_r($key);
}

If send simple data in array i can fetch easy as

$fields = array(
                        'lname' => urlencode($last_name),
                        'fname' => urlencode($first_name),

                );

$fields_string='';

foreach($fields as $key=>$value) { 
    print_r("$key"." ".$value);

    $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); 

and the get-post as

print_r($_POST);

there is any solution for curl that we can send dynamic data and retrieve it.

Thanks and regards.

Upvotes: 0

Views: 3224

Answers (2)

user3840898
user3840898

Reputation: 197

$query="select * from phone_gap";
$query=  mysql_query($query);

while ($row = mysql_fetch_assoc($query)) {
 $fields[]=$row;
}

$str = http_build_query($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $str);

//execute post
$result = curl_exec($ch);
echo $result;

and use in get-post.php

echo ""; print_r($_POST);

Upvotes: 2

Randhir
Randhir

Reputation: 765

You need not pass post as multidimensional array , just use curl post like this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);

Pass your $fields variable direct to post instead using it in $data array. This would work for you.

Upvotes: 0

Related Questions