无法使用cURL在php中执行POST请求

时间:2015-09-03 10:31:18

标签: php curl ldap

我无法在php中执行POST请求,以下是我的代码:

 $ch = curl_init();
 $fields = "=var1?var2?var3";
 $url = "http://localhost/Profile.php?";
 curl_setopt($ch, CURLOPT_URL,$url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch, CURLOPT_HEADER, FALSE);
 curl_setopt($ch, CURLOPT_POST,true);
 curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
 $output = curl_exec($ch);
 curl_close($ch);

profile.php:

print_r($_POST);

似乎没有任何东西在页面上显示只是一个空数组,如果我通过GET它可以工作。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您的$fields字符串格式应为"key1=value1&key2=value2...",而不是前缀=。所以,在你的情况下:

$fields = "key1=var1&key2=var2&key3=var3";

此外,代码中的print_r($_POST)命令将呈现已将发布到页面的内容,而不是 页面。

答案 1 :(得分:0)

//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
                        'lname' => urlencode($last_name),
                        'fname' => urlencode($first_name),
                        'title' => urlencode($title),
                        'company' => urlencode($institution),
                        'age' => urlencode($age),
                        'email' => urlencode($email),
                        'phone' => urlencode($phone)
                );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

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

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

//close connection
curl_close($ch);