SOAP IP Address in PHP

This is an example about how to perform SOAP IP Address petitions over a certain IP address in php.

It can be useful in several situations. For instance, if you have a bunch of server behind a load balancer, all of them hosting the same sites (virtual hosts), and you need to comunicate directly to each of them. If you know the server’s ip address, you can comunicate directly to them by specifying the ip address and the host.
Basically, we need to extend the SoapClient class, overriding the __doRequest method in a way that allows us to specify a custom header in the HTTP petitions.

class HostSoapClient extends SoapClient {

 const DEBUG = true;

/*
 * Override the method __doRequest to perform a custom CURL petition, specifying a host on the header
 *
 * @param $request string
 * @param $location sting
 * @param $action string contain the host and the action in the format url#action
 * @param $version int
 * @param $one_way int
 * @return string
 */
 public function __doRequest($request, $location, $action, $version, $one_way = 0) {
 $url_parts = parse_url($location);
 $ch = curl_init();
 list($host, $action) = explode('#', $action);
 if(self::DEBUG) {
 echo 'Performing request to: ' . $location . "\n";
 echo 'Host specified on the header: ' . $host . "\n";
 echo 'Request:' . $request . "\n";
 }
 curl_setopt($ch,CURLOPT_URL, $location);
 curl_setopt($ch,CURLOPT_POSTFIELDS, $request);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: ' . $host, 'SoapAction: ' . $action));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $response = curl_exec($ch);
 curl_close($ch);
 return $response;
 }
}

Usage example:

$server = '11.22.33.44'; //The ip address where the page is hosted
$url = $server . '/api/index/index'; //Path of the api (tested on both v1 and v2)
$host = 'www.yourhost.com'; //An existing hostname on the $server ip
$client = new HostSoapClient(null,
		array('trace' => 1,
			'exceptions' => 1,
			'cache_wsdl' => 0,
			'location'=> $url,
			'uri' => $host));
$session = $client->login('user', 'pass');
//Now you are connected and you can call any resource, ie.
$client->call($session, 'api.method', array('param', 'value'));

One thought on “SOAP IP Address in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *