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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

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?