HTML/PHP Post method to different server

前端 未结 3 1736
青春惊慌失措
青春惊慌失措 2020-12-15 13:34

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 po

相关标签:
3条回答
  • 2020-12-15 13:51
    <form method="POST" action="http://the.other.server.com/script.php">
    
    0 讨论(0)
  • 2020-12-15 13:57

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

    How do I use arrays in cURL POST requests

    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

    0 讨论(0)
  • 2020-12-15 14:11

    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.

    //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 action attribute:

    <form action="http://some-other-server.com" method="POST">
    
    0 讨论(0)
提交回复
热议问题