HTML/PHP Post 方法到不同的服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9065765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:04:56  来源:igfitidea点击:

HTML/PHP Post method to different server

phphtmlpost

提问by rom

I want to create a POST method form that sends details to a PHP script on another server (ie, not its localhost). Is this even possible? I imagine GET is fine, so is POST possible?

我想创建一个 POST 方法表单,将详细信息发送到另一台服务器(即,不是其本地主机)上的 PHP 脚本。这甚至可能吗?我想 GET 很好,那么 POST 可能吗?

回答by Marc B

<form method="POST" action="http://the.other.server.com/script.php">

回答by MMM

If you want to do that on your server (i.e. you want your server to act as a proxy) you can use cURL for that.

如果您想在您的服务器上执行此操作(即您希望您的服务器充当代理),您可以使用 cURL。

//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://domain.com/get-post.php';
$fields_string = "";
$fields = array(
        'lname'=>urlencode($last_name), // Assuming there was something like $_POST[last_name]
        'fname'=>urlencode($first_name)
    );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = 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);

However if you just simply want to send a POST request to another server, you can just change the actionattribute:

但是,如果您只是想将 POST 请求发送到另一台服务器,则只需更改action属性:

<form action="http://some-other-server.com" method="POST">

回答by mishawagon

There is another question on Stack Overflow that shows a better way to url-ify the variables. It is better because the method shown in the answer above breaks when you use nested associative arrays (aka hashes).

Stack Overflow 上还有另一个问题,它展示了一种更好的方法来对变量进行 url 化。更好,因为当您使用嵌套关联数组(又名哈希)时,上面答案中显示的方法会中断。

How do I use arrays in cURL POST requests

如何在 cURL POST 请求中使用数组

If you are really wanting to build that query string manually, you can. However, http_build_query will make your "url-ify the data for the POST" section unnecessary. – Benjamin Powers Nov 28 '12 at 2:48

如果您真的想手动构建该查询字符串,则可以。但是,http_build_query 将使您的“对 POST 的数据进行 url-ify”部分变得不必要。– 本杰明·鲍尔斯 2012 年 11 月 28 日 2:48