如何以curl发送和接收数据

时间:2014-11-21 05:51:11

标签: php curl

我使用以下内容发送和接收数据如下

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

?>

和get-post.php

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

如果在数组中发送简单数据,我可以轻松获取

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

和get-post为

的print_r($ _ POST);

有任何curl解决方案,我们可以发送动态数据并检索它。

谢谢和问候。

2 个答案:

答案 0 :(得分:1)

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

并在get-post.php中使用

回声“”;的print_r($ _ POST);

答案 1 :(得分:0)

你不需要将帖子作为多维数组传递,只需像这样使用curl post:

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

将$ fields变量直接传递给post,而不是在$ data数组中使用它。这对你有用。