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

时间:2017-07-26 23:29:44

标签: php forms api post

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

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

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

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

2 个答案:

答案 0 :(得分:3)

http_build_query

  

(PHP 5,PHP 7)http_build_query - 生成URL编码的查询字符串

示例:

curl

以上示例将输出:

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

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

?>

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

从此answer

  

使PHP执行POST请求的最简单方法可能就是使用   cURL,可以是extension,也可以只是对另一个人进行炮轰   处理。这是一个帖子样本:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

答案 1 :(得分:0)

连接url并使用Module Module1 Sub Main() Dim arr() = Environment.GetCommandLineArgs For Each arg As String In arr Console.WriteLine(arg) Next Console.ReadLine() End Sub End Module

发布post方法
file_get_contents

您也可以使用if(isset($_POST['submit'])) { $var1 = $_POST['var1']; $var2 = $_POST['var2']; $url = 'https://api.this.com/foo/bar?token=IHAVETOKEN&foo='.$Var1. '&bar='.$var2; $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded' ) ); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); header("Location: thankyou.php"); }