Web Services - Client Server communication using SOAP

Web services are client and server applications that communicate over the World Wide Web's (WWW) HyperText Transfer Protocol (HTTP).

  • By using Web services, your application can publish its function or message to the rest of the world.
  • Web services use XML to code and to decode data, and SOAP to transport it (using open protocols).
  • Web services are open standard ( XML, SOAP, HTTP etc.) based Web applications that interact with other web applications for the purpose of exchanging data

WSDL (Web Services Description Language)

  • WSDL is a language for describing web services and how to access them.
  • It is written in XML.
  • It specifies the location of the service and the operations (or methods) the service exposes.
     

SOAP (Simple Object Access Protocol)

  • Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML.
  • Communication between the web service and client happens using XML messages.

Web Services - SERVER

http://webservices-server.pachabhaiya.com

 

1. Create database


CREATE DATABASE IF NOT EXISTS `db_webservices`;

USE `db_webservices`;

CREATE TABLE IF NOT EXISTS `tbl_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100),
`email` varchar(100),
`website` varchar(100),
`date_created` datetime,
CONSTRAINT user_user_id_pk PRIMARY KEY (user_id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2. Create PHP class file having functions to insert and select the user informations.
classes/class.user.php


<?php
/**
 * class.user.php
 * @author Chhabi Pachabhaiya <info@c.pachabhaiya.com>
 */

require_once("config.php");
require_once("classes/class.db.php");

class User extends Db
{
    public function __construct()
    {
        parent::__construct(HOSTNAME, USERNAME, PASSWORD, DATABASE_NAME, PORT);
        $this->mysqli = $this->real_connect();
    }

    public function insertUser($name, $email, $website)
    {
        $sql = "INSERT INTO tbl_user (name, email, website, date_created) VALUES ('".addslashes($name)."', '".addslashes($email)."', '".addslashes($website)."', NOW())";
        $res = $this->mysqli->query($sql, MYSQLI_STORE_RESULT);
        if ($this->mysqli->affected_rows > 0) {
            $return = "INSERT SUCCESS";
        } else {
            $return = "INSERT FAILED";
        }
        return $return;
    }

    public function selectUser($user_id = NULL)
    {
        $return = array();
        $sql = "SELECT user_id, name, email, website, date_created";
        $sql .= " FROM tbl_user";
        if ($user_id != NULL) {
            $sql .= " WHERE user_id = $user_id";
        }
        $sql .= " ORDER BY date_created DESC";
        $res = $this->mysqli->query($sql, MYSQLI_STORE_RESULT);
        if ($res->num_rows > 0) {
            while ($row = $res->fetch_object()) {
                $data = array('user_id' => $row->user_id,
                'name' => stripslashes($row->name),
                'email' => stripslashes($row->email),
                'website' => stripslashes($row->website),
                'date_created' => $row->date_created);
                array_push($return, $data);
            }
        }
        $res->free();
        return $return;
    }
}

3. Create WSDL (user.php) - WSDL 1.1 / SOAP 1.1


<?php
if (stristr($_SERVER['QUERY_STRING'], "wsdl")) {
    header('Content-type: application/xml; charset=utf-8');
?>
<definitions name="WebServices11"
    targetNamespace="urn:WebServices11"
    xmlns:tns="urn:WebServices11"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:xsd="http://www.w3.org/2000/10/XMLSchema"
    xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
    xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">

    <types>
        <xsd:schema targetNamespace="urn:WebServices11" xmlns="http://www.w3.org/2000/10/XMLSchema">
            <xsd:element name="insertUserRequest">
                <xsd:complexType>
                    <xsd:sequence>
                        <xsd:element name="user_id" type="xsd:integer" />
                        <xsd:element name="name" type="xsd:string" />
                        <xsd:element name="email" type="xsd:string" />
                        <xsd:element name="website" type="xsd:string" />
                    </xsd:sequence>
                </xsd:complexType>
            </xsd:element>
            <xsd:element name="insertUserResponse">
                <xsd:complexType>
                    <xsd:all>
                        <xsd:element name="return" type="xsd:string" />
                    </xsd:all>
                </xsd:complexType>
            </xsd:element>
            <xsd:element name="selectUserRequest">
                <xsd:complexType>
                    <xsd:sequence>
                        <xsd:element name="user_id" type="xsd:integer" />
                    </xsd:sequence>
                </xsd:complexType>
            </xsd:element>
            <xsd:element name="selectUserResponse">
                <xsd:complexType>
                    <xsd:complexContent>
                        <xsd:restriction base="soapenc:Array">
                            <xsd:attribute ref="soapenc:arrayType" arrayType="tns:objUser[]" />
                        </xsd:restriction>
                    </xsd:complexContent>
                </xsd:complexType>
            </xsd:element>
        </xsd:schema>
    </types>

    <message name="insertUserRequest">
        <part name="user_id" type="xsd:integer" />
        <part name="name" type="xsd:string" />
        <part name="email" type="xsd:string" />
        <part name="website" type="xsd:string" />
    </message>

    <message name="insertUserResponse">
        <part name="return" type="xsd:string" />
    </message>

    <message name="selectUserRequest">
        <part name="user_id" type="xsd:integer" />
    </message>

    <message name="selectUserResponse">
        <part name="return" type="tns:objUser" />
    </message>

    <portType name="WebServices11PortType">
        <operation name="insertUser">
            <documentation>Add the user record</documentation>
            <input message="insertUserRequest" />
            <output message="insertUserResponse" />
        </operation>
        <operation name="selectUser">
            <documentation>Get the user record</documentation>
            <input message="selectUserRequest" />
            <output message="selectUserResponse" />
        </operation>
    </portType>

    <binding name="WebServices11SoapBinding" type="tns:WebServices11PortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
        <operation name="insertUser">
            <soap:operation soapAction="urn:WebServices11InsertUserAction" />
            <input>
                <soap:body use="encoded" namespace="urn:WebServices11" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
            </input>
            <output>
                <soap:body use="encoded" namespace="urn:WebServices11" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
            </output>
        </operation>
        <operation name="selectUser">
            <soap:operation soapAction="urn:WebServices11SelectUserAction" />
            <input>
                <soap:body use="encoded" namespace="urn:WebServices11" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
            </input>
            <output>
                <soap:body use="encoded" namespace="urn:WebServices11" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
            </output>
        </operation>
    </binding>

    <service name="WebServices11Service">
        <port name="WebServices11Port" binding="tns:WebServices11SoapBinding">
            <soap:address location="http://webservices-server.pachabhaiya.com/user_server.php" />
        </port>
    </service>
</definitions>
<?php
}
else
{
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Web Services</title>
</head>

<body>
<h1>Web Services Example (PHP, MySQL, WSDL 1.1, SOAP, XSD)</h1>
<p>
    Author: Chhabi Pachabhaiya {<a href="http://c.pachabhaiya.com" target="_blank">http://c.pachabhaiya.com</a>}
</p>
<p>Web Services URL: <a href="http://webservices-server.pachabhaiya.com/user.php?wsdl" target="_blank">http://webservices-server.pachabhaiya.com/user.php?wsdl</a></p>
</body>
</html>
<?php
}
?>

types, which provides data type definitions used to describe the messages exchanged.
message, which represents an abstract definition of the data being transmitted. A message consists of logical parts, each of which is associated with a definition within some type system.
portType, which is a set of abstract operations. Each operation refers to an input message and output messages.
binding, which specifies concrete protocol and data format specifications for the operations and messages defined by a particular portType.
port, which specifies an address for a binding, thus defining a single communication endpoint.
service, which is used to aggregate a set of related ports.

4. Create Web Services Server script (user_server.php)


<?php
ini_set("session.auto_start", 0);
session_start();

if (!extension_loaded("soap"))
{
    dl("php_soap.dll");
}
ini_set("soap.wsdl_cache_enabled","0");

require_once("classes/class.user.php");

$server = new SoapServer("http://webservices-server.pachabhaiya.com/user.php?wsdl");
$server->setClass("User");
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();

Web Services - CLIENT

http://webservices-client.pachabhaiya.com

1. Web Services client using SoapClient function (soap_client.php)
http://webservices-client.pachabhaiya.com/soap_client.php


<?php
if(!extension_loaded("soap"))
{
    dl("php_soap.dll");
}
ini_set("soap.wsdl_cache_enabled","0");

$client = new SoapClient("http://webservices-server.pachabhaiya.com/user.php?wsdl");

$name = isset($_GET['name']) ? $_GET['name'] : 'Chhabi Pachabhaiya';
$email = isset($_GET['email']) ? $_GET['email'] : 'info@c.pachabhaiya.com';
$website = isset($_GET['website']) ? $_GET['website'] : 'http://c.pachabhaiya.com';

// Insert user record
$return = $client->insertUser($name, $email, $website);
echo $return;

echo "<br><br>";

// Print user record
// $user = $client->selectUser('20'); // select single user having user_id=20
$user = $client->selectUser();
foreach ($user as $val) {
    echo $val['date_created'] . ' :: ' . $val['name'] . " [" . $val['email'] . "] : " . $val['website'];
    echo "<br /><br />";
}

 

2. Web Services client using nusoap (soap_client_nusoap.php)
http://webservices-client.pachabhaiya.com/soap_client_nusoap.php


<?php
require_once("nusoap-0.9.5/lib/nusoap.php");

$wsdl = "http://webservices-server.pachabhaiya.com/user.php?wsdl";
$client = new nusoap_client($wsdl, true);

// Add user record
$param_insertuser = array('Chhabi Pachabhaiya','info@c.pachabhaiya.com','http://c.pachabhaiya.com');
$result = $client->call('insertUser', $param_insertuser);
print $result;

echo "<br><br>";

// Print user records
//$param_selectuser = array('user_id' => 20); // select single user having user_id=20
$param_selectuser = array();
$user = $client->call('selectUser', $param_selectuser);
foreach ($user as $val) {
    echo $val['date_created'] . ' :: ' . $val['name'] . " [" . $val['email'] . "] : " . $val['website'];
    echo "<br /><br />";
}

 

Important links:

http://www.w3.org/TR/wsdl
http://www.w3schools.com/webservices/default.asp
http://sourceforge.net/projects/nusoap/

 

Attachments
https://drive.google.com/open?id=0B4sAau9_Z97hVHhhMWNlWTI0eFk
https://drive.google.com/open?id=0B4sAau9_Z97hSDZfakppMGt5TnM