【问题标题】:HTML/PHP Post method to different serverHTML/PHP Post 方法到不同的服务器
【发布时间】:2012-02-22 08:36:49
【问题描述】:

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

【问题讨论】:

    标签: php html post


    【解决方案1】:
    <form method="POST" action="http://the.other.server.com/script.php">
    

    【讨论】:

    • 这很好,但问题是:POST 数据是否真的在外部 php 脚本中被接收到? post数据不是由apache在本地处理的吗?
    • 数据转到您在action 中指定的任何 URL。如果它完全在另一台服务器上,它会去那里并且永远不会触及加载表单的服务器。
    • @rom — POST 数据由接收 HTTP 请求的服务器“本地”处理。
    • 收到了。唯一可能导致它似乎没有收到的可能性:a)您用于值的名称不同 b)它检查引用者。
    • @Ben D:完全错误。 POST 数据在消息正文中发送。 GET 数据位于“标题中”,因为它是请求的 URL 的一部分。
    【解决方案2】:

    如果您想在您的服务器上执行此操作(即您希望您的服务器充当代理),您可以使用 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);
    

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

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

    【讨论】:

    • 我只是不知道可以跨服务器发布。我不知道 POST 方法是如何工作的。谢谢。
    【解决方案3】:

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

    How do I use arrays in cURL POST requests

    如果您真的想手动构建该查询字符串,您可以。但是,http_build_query 将使您的“url-ify the data for the POST”部分变得不必要。 – Benjamin Powers 2012 年 11 月 28 日 2:48

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多