5 April 2017

Simple PHP SOAP Client

As I need a SOAP client here and there - especially when it comes to web-based projects like monitoring and so on, I created a little SOAP Client in PHP after searching for a simple solution without any additional features. Feel free to use it for whatever:

soap_config.php

define('SOAP_URI', 'urn:ENDPOINT'); // SOAP URI - please consider the documentation of your SOAP service to figure this one out
define('SOAP_IP', 'ip or hostname'); // IP/host of the server offering the SOAP service
define('SOAP_PORT', '8080'); // SOAP Port
define('SOAP_USER', 'accountname'); // Username of the account to be used via the SOAP Client
define('SOAP_PASS', 'somepassword'); // password for the account to be used via the SOAP Client

soap_client.php:

class soap {
  private $soap;
  private $messages = array();

  public function __construct() {
    try {
            $this -> connect();
        }
    catch (Exception $e) {
            $this -> addMessage($e -> getMessage());
        }
    }
    public function connect() {
        $this -> soap = new SoapClient(NULL, array(
            'location'=> 'http://'. SOAP_IP .':'. SOAP_PORT .'/',
            'uri' => SOAP_URI,
            'style' => SOAP_RPC,
            'login' => SOAP_USER,
            'password' => SOAP_PASS,
            'keep_alive' => false
        ));
    }
  public function cmd($command) {
    $result = $this -> soap -> executeCommand(new SoapParam($command, 'command'));
    $this -> addMessage($result);
    return true;
  }
  public function addMessage($message) {
    $this -> messages[] = $message;
    return true;
  }
  public function getMessages() {
    return $this -> messages;
  }
}

soap_example.php:

//please don't EVER use this example on a productive system
require("soap_config.php");
require("soap_client.php");

$soap = new soap();
$soap->cmd('Command-To-Send-To-The-SOAP-Interface');
var_export($s->getMessages());

Comments: