php - 使用 PHP 将表单数据发送/发布到 URL

标签 php forms api post

关闭。这个问题需要details or clarity .它目前不接受答案。












想改善这个问题吗?通过 editing this post 添加详细信息并澄清问题.

4年前关闭。




Improve this question




我有一个通过 POST 提交的表单,一旦提交表单,我就会捕获变量。

如何连接表单数据,然后将其发布到 url,然后重定向到感谢页面?

这不是确切的代码,我只是找不到任何正常的答案,而且我确信有不止一种方法可以做到这一点。只是想找出最简单的方法。

if(isset($_POST['submit'])){
    $var1 = $_POST['var1'];
    $var2 = $_POST['var2'];

$url = 'https://api.this.com/foo/bar?token=IHAVETOKEN&foo=$Var1&bar=$var2'

post_request_to($url);

header("Location: thankyou.php");
}

编辑:

这是实际答案/工作代码:
if(isset($_GET['submit'])){
  $firstName = $_GET['firstname'];
  $lastName = $_GET['lastname'];
  $email = $_GET['email'];
  $password = $_GET['password'];
  $phone = $_GET['phone'];
}

  $data = array(
        'token' => 'sadfhjka;sdfhj;asdfjh;hadfshj',
        'firstName' => $firstName,
        'lastName' => $lastName,
        'email' => $email,
        'password' => $password,
        'phone' => $phone

    );


  $postvars = http_build_query($data) . "\n";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://api.com/foo/bar?');
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $server_output = curl_exec ($ch);

  curl_close ($ch);

最佳答案

http_build_query

(PHP 5, PHP 7) http_build_query — Generate URL-encoded query string



例子:
<?php
$data = array(
    'foo' => 'bar',
    'baz' => 'boom',
    'cow' => 'milk',
    'php' => 'hypertext processor'
);

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&amp;');

?>

上面的例子将输出:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

其余的取决于您的流程逻辑。要发布到另一个脚本:

从这里 answer :

Possibly the easiest way to make PHP perform a POST request is to use cURL, either as an extension or simply shelling out to another process. Here's a post sample:


// where are we posting to?
$url = 'http://foo.com/script.php';

    // what post fields?
    $fields = array(
       'field1' => $field1,
       'field2' => $field2,
    );

    // build the urlencoded data
    $postvars = http_build_query($fields);

    // 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, $postvars);

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

    // close connection
    curl_close($ch)

关于php - 使用 PHP 将表单数据发送/发布到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339010/

相关文章:

php - 阻止页面加载

PHP session - 登录后未存储用户

node.js - 如何在一定时间内阻止api重复请求

swift - 如何传递 tumblr api GDPR 信息并获取 JSON?

php - 在生产服务器上启用 XDebug 会使 PHP 变慢吗?

PHP - 文件编辑表单显示空白

即使在 Windows 上后台运行命令后,PHP 脚本仍停留在 exec 上

jquery - 如何 append 文本区域值以遍历数组

php - w3 验证器给出了我的导航错误

api - 使用可点击的机器人命令发送 Telegram 消息