簡體   English   中英

無法使用cURL在php中執行POST請求

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

我無法在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進行操作,則似乎沒有任何內容在頁面上僅顯示一個空數組。 我做錯了什么?

您的$fields字符串應采用"key1=value1&key2=value2..."的格式,且不得帶= 因此,在您的情況下:

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

此外, 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