Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Post to Another Server then Return the Other Server's Response

Tags:

post

php

adapter

I have a couple of servers, which are working together.

  • Server A gives an xml response to posts that come in.
  • Server B takes a post request, modifies the post values slightly then does a post to server A (think adapter pattern). Server B should then wait for Server A's xml response and then return that response.

Is there an easy way to do this with build in features of php?

like image 561
James Oravec Avatar asked Oct 21 '13 16:10

James Oravec


2 Answers

I had a similar need for one of my scripts and was able to do so using the following,

$url = URL_TO_RECEIVING_PHP;

$fields = array(
        'PARAM1'=>$_POST['PARAM1'],
        'PARAM2'=>$_POST['PARAM2']
);

$postvars='';
$sep='';
foreach($fields as $key=>$value)
{
        $postvars.= $sep.urlencode($key).'='.urlencode($value);
        $sep='&';
}

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$result = curl_exec($ch);

curl_close($ch);

echo $result;

It will echo out what is returned from your receiving PHP.

like image 115
Ryan Lombardo Avatar answered Oct 16 '22 11:10

Ryan Lombardo


Have a look at cURL: http://php.net/manual/en/book.curl.php

That should allow you to modify the $_POST array, send the modified values on to the other server, and deal with the response.

Also, see here : PHP: send POST request then read XML response?

like image 1
Tom Macdonald Avatar answered Oct 16 '22 13:10

Tom Macdonald