我正在尝试将 HTML 表单值作为 CURLOPT_FIELDS
发送。我的 HTML 表单:
<form class="form-response" method="POST" action="postform.php">
<h2 class="form-response-heading">get Response</h2>
<input name="phonenumber" class="form-control" type="text" autofocus="" required="" placeholder="phonenumber">
<button class="btn btn-lg btn-primary btn-block" type="submit">Get Response</button>
</form>
目前我的 postform.php
是:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.com/AccountDetails",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"phonenumber\":\"6282818966317\", \"FullName\":\"Jenny Doe\" }",
CURLOPT_HTTPHEADER => array(
"accept: application/json;charset=UTF8",
"api-key: myapikeynumbers",
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
我尝试了 HTML 表单将值传递到 CURLOPT_POSTFIELDS => "{\"phonenumber\":\"6282818966317\"}",
到目前为止,如果我手动添加电话号码,postform.php
将返回响应。我想要做的是 CURLOPT_POSTFIELDS
将自动从 HTML 表单输入的 phonenumber
获取值。
最佳答案
您需要将值存储在变量中并传递该变量。
//Somewhere up here, store the post data in a variable something like this:
$phone = $_POST['phonenumber'];
$fullName = $_POST['full_name'];
CURLOPT_POSTFIELDS => "{ \"phonenumber\":\"" .$phone . "\", \"FullName\":\"" . $fullName . "\" }",
我发现将输入存储在变量中可以让您更轻松地使用它们。根据您上面的评论,您可能需要查看文档以了解您要连接的 API 的期望,并在发送之前验证输入是否有效。
关于php - 如何将值从 HTML 表单传递到 CURLOPT_POSTFIELDS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54992478/