php - 如何将值从 HTML 表单传递到 CURLOPT_POSTFIELDS

标签 php curl

我正在尝试将 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/

相关文章:

php - wordpress functions.php 没有为 CSS 显示任何内容

php - 在sql查询中创建计数器

php - 将输入传递给 C 程序并使用 php 获取输出

php - 如何从动态创建的php表中收集数据

cakephp - 未从 cron 中找到带有 OpenSSL 的 Libcurl

laravel - Laravel 应用程序关闭时会触发什么事件?

php - Laravel Eloquent 选择问题

php - PHP-CURL 的 curl_multi_exec 内部真的是多线程的吗?

php - 使用 header application/x-www-form-urlencoded curl 发布

http - 发送 HTTP 请求告诉服务器只返回 header 而不返回正文?