简体   繁体   English

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

[英]Unable to perform a POST request in php using cURL

I am unable to perform a POST request in php, the following is my code: 我无法在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: profile.php:

print_r($_POST);

Nothing seems to be displaying on the page just an empty array, if I do via GET it works. 如果我通过GET进行操作,则似乎没有任何内容在页面上仅显示一个空数组。 What have I done wrong? 我做错了什么?

Your $fields string should be in the format "key1=value1&key2=value2..." , without a prepended = . 您的$fields字符串应采用"key1=value1&key2=value2..."的格式,且不得带= So, in your case: 因此,在您的情况下:

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

Additionally, the print_r($_POST) command in your code will render what has been POSTed to your page, not by your page. 此外, print_r($_POST)在你的代码的命令将呈现什么已经张贴您的网页,而不是你的页面。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM