How to submit form on an external website and get

2019-03-30 01:36发布

I would like make a script using PHP (probably need JS) to send POST data to another webpage and get the result back.

For example, Domain A will have a form with a textbox and submit button, and Domain B will have a script which will fill the textbox and press the submit button and return the generated HTML page.

3条回答
你好瞎i
2楼-- · 2019-03-30 01:58

--- Original 2012 Answer ---

Use jquery; just load the page with a $.ajax() call. If you need to, you can use "jsonp" which works around the restrictions between calling pages from different domains.

The nice thing about using javascript is that you don't need any serverside languages.

--- 2018 edit ---

I realise now that you can't do a POST with jsonp (as it is essentially read-only) so this will only work if the website accepts the form as a GET (ie, the parameters in the URL). Otherwise, best to use Curl or similar as suggested in other answers.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-30 01:59

The following lines of code can be written on another php script,

//set POST variables
$url = 'the website from which you need data through post';
$fields = array(
            //post parameters to be sent to the other website
            'text'=>urlencode($_POST['text']), //the post request you send to this  script from your domain.
        );

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

Now $result will contain the text received from the other website.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-03-30 02:06

With JS: for security reasons not. Read on Same origin policy.

With PHP you can do what you want, including POSTing other servers. For example use CURL.

查看更多
登录 后发表回答