HTML/PHP Post method to different server

前端 未结 3 1742
青春惊慌失措
青春惊慌失措 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 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:

提交回复
热议问题