Click here to Skip to main content
Click here to Skip to main content

Tagged as

Webservice Client and Server demo in PHP

, 27 Aug 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Demo of 6 completely different webservices also with SOAP

Introduction

This article demonstrates how different webservices work. The article is for beginners so the source code is kept simple.

  • The source code contains 6 different webservice clients and 2 webservice servers.
  • All examples are programmed in PHP 5, so they run on Windows and Linux.
  • Some samples send the requests via GET and others use POST.
  • Some samples send the requests via URL and others use SOAP.
  • The code does NOT use any PHP Soap libraries as the intention is to show from scratch how to build and send the HTTP request.
  • Additionally the article shows how to parse XML responses and how to use XPath.
  • The samples are based on a reusable webservice client class.
  • The intention of the code is to show the basics of webservices. Complex topics like WSDL are not covered.
  • If you never used PHP, you will find a beginner tutorial at the end of the article on how to install and run the samples on Windows.

After reading this article and studying the samples, you will notice that there is no webservice which equals another one. They ALL have their own individual characteristics.

Webservice Client Yahoo Maps

This sample demonstrates how to send an address to the Yahoo Maps webservice which then returns the GPS coordinates (longitude and latitude).

This webservice receives the parameters via GET in the URL.
The client demonstrates how to extract the data from the returned XML data using XPath.

Server: http://local.yahooapis.com/MapsService/V1/geocode

Request:

Street = 701 First Ave, City = New York, State = NY

Response:
--- RESULT 1 ---
Precision: address
Address:   701 1st Ave
ZIP:       11232
Latitude:  40.656335
Longitude: -74.012770

Webservice Client Weather

This sample demonstrates how to obtain the current weather data of one of 10,000 cities in the world.
Each city is represented by a city code (e.g. NLXX0002 for Amsterdam, Netherlands).
You can choose to see results in Celsius, kilometer, kilometer/h and millibar or Fahrenheit, miles, miles/h, inch.
You can also get the weather forecast hourly or daily up to 10 days in advance. But this is not included to keep the sample simple.

This webservice receives the parameters via GET in the URL.
The client demonstrates how to extract the data from the returned XML data using XPath.

Server: http://xml.weather.com/weather/local

Request:

City= NLXX0002, Count of forecast days = 0, Units = European

Response:
Location:     Amsterdam, Netherlands
Local Time: 5:53 PM
Sunrise:       6:40 AM
Sunset:        8:44 PM
Longitude:  4.90
Latitude:     52.35



Sky:                     Partly Cloudy
Temperature:    18°C
Feels Like:         18°C
Dew Point:         13°C
Pressure:           1010.8 mb
Humidity:           73%
Visibility:            10.0 km
Wind Speed:      21 km/h
Wind Direction: WSW
UV Index:           2


Moon:  Waxing Crescent
WeatherStation: Amsterdam, NETHERLANDS

Webservice Client Amazon SimpleDB

This webservice connects with the database webservice of Amazon.

Before reading on, please hold your breath for a while and forget everything you know about Amazon!! This webservice has absolutely NOTHING to do with any of the products you can buy on Amazon like books, CDs or DVDs.

Amazon offers a webservice which allows to store your data of any type on their web database servers where you can create your own private database (domain). So you can write (web) applications which store data in the Amazon database. The advantage is that you can access this database from all over the world, that you can store large data (like video files) and that Amazon offers very fast servers which are connected directly to an internet backbone. Obviously this service is not for free.
In the source code, you find the URL where to subscribe and where you get your private and public key you need. But if you don't have subscribed with valid billing information (e.g. MasterCard), you will still get an error although you have valid keys and although the first 1GB traffic every month is gratis.

This sample is interesting because it shows how a client is validated. To avoid that someone else uses the account that you are paying for, all requests to the server must contain your public key with which you identify yourself and all data fields must then be signed with your private key. The signing is done with the PHP command hash_hmac().

The action "CreateDomain" creates a new database with the given name "TestDomain".
The request must also send a valid UTC timestamp. If the time is wrong, the request is rejected by the server. The data is sent via POST.

Server: https://sdb.amazonaws.com

Request:
Action                     = CreateDomain
AWSAccessKeyId = AIWMFIAEQGPKI3LFRADW
DomainName        = TestDomain
SignatureMethod = HmacSHA256
SignatureVersion = 1
Timestamp            = 2009-08-25T15:57:40.000Z
Version                   = 2009-04-15
Signature               = Xp3QbA4G4Ws41aZ7LX80i8Z4WRqL6LmsIKX9P8DLluY=

Webservice Client + Server Math calculation

This sample is a pair of Client and Server.
It shows how simple it is to write a webservice server.

Server and client both run on localhost.

What it does is very simple: the client sends a mathematical operation like add or multiply and two numbers.
The server calculates the result and returns it as XML.
The data is sent via POST.

Request:
Operation = Multiply
Value1      = 21
Value2      = 3

Response:
Result      = 63

Webservice Client + Server String Operation

This sample is similar to the previous one except that it uses SOAP.
The client sends a string and the server executes an operation on it like reverting it, or making it uppercase.

Server and client both run on localhost.

For many SOAP servers, it is important to set the HTTP header field "SOAPAction".
It is not very logical that you send a XML document which could also contain a XML field "SOAPAction" and the server additionally wants a HTTP header to be set.
But depending on the server, you may get an error if this HTTP header does not exist.

Request:

POST /webservice/Server_Soap.php HTTP/1.0
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: 260
SOAPAction: STR_RevertRQ
User-Agent: PHP WebService Client

<?xml version="1.0"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
        <STR_RevertRQ>
           <Message>This is a little Text</Message>
       </STR_RevertRQ>
    </soapenv:Body>
</soapenv:Envelope>

Response:

<?xml version="1.0"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
        <STR_RevertRS TimeStamp="1251219075">
            <Message>txeT elttil a si sihT</Message>
        </STR_RevertRS>
    </soapenv:Body>
</soapenv:Envelope>

Webservice Client Sabre

Sabre is a webservice which returns flight and hotel data for the tourism industry. You can book flights, hotels and rent cars via this webservice. Sabre is member of the Open Travel Alliance (OTA).

Obviously you must subscribe and pay for this service. The developer documentation is only available for paying clients.

Server: https://webservices.sabre.com/websvc

This sample sends a OTA_PingRQ to the server which is the simplest command of the large list of OTA commands.
The server should respond with OTA_PingRS response which echoes the same string back.
I never got this to work. If you know how to fix it, send me an email!

How to Run the Samples on Windows

  1. First check that there is no program on your PC which runs a server on Port 80.
    If you have installed Skype, make sure that under the menu Tools -> Options -> Connection, the checkbox "Use Port 80 and 443 as alternatives for incoming connections" is NOT checked!!
  2. Second check that your browser does not have a Proxy server for HTTP configured. If so, turn it off!
  3. Install Wamp Server which includes Apache, mySql and PHP into C:\Program Files\Wamp.
  4. Open the file C:\Program Files\Wamp\bin\apache\Apachex.y.z\bin\php.ini
    and remove semicolon in the line ;extension=php_openssl.dll
  5. After that, start the Server from the startmenu. You will find a new symbol in your Icon Tray which you can left click to open the configuration menu.
    But there is nothing that must be configured: Wamp runs out of the box.
  6. Copy the entire content of the ZIP file from CodeProject into the folder C:\Program Files\Wamp\www\webservice
  7. If you did it correctly this file will exist: C:\Program Files\Wamp\www\webservice\index.php
  8. Open your browser and enter http://localhost/webservice

Subscription

For those webservices which require subscription, you can find the links and more information in the source code comments.

Elmü

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Elmue
Software Developer (Senior) ElmüSoft
Chile Chile
Software Engineer since 27 years.

Comments and Discussions

 
QuestionWeb Service PinmemberConSoft5-Mar-13 5:28 
QuestionInvalid URL PinmemberRay Yang20-Sep-12 2:20 
AnswerRe: Invalid URL PinmemberElmue22-Sep-12 4:55 
QuestionThanks PinmemberMilad.D10-Sep-12 6:17 
QuestionProblem in Client_Math.php Pinmemberadamarul30-Apr-12 21:39 
AnswerRe: Problem in Client_Math.php PinmemberElmue3-May-12 15:01 
GeneralMy vote of 5 Pinmembermanoj kumar choubey23-Feb-12 20:32 
Questionhave you find solution for sabre web service ? PinmemberMilan Prajapati18-Aug-10 20:06 
AnswerRe: have you find solution for sabre web service ? PinmvpElmue19-Aug-10 4:13 
GeneralRe: have you find solution for sabre web service ? PinmemberVinfo18-Jun-12 7:43 
GeneralRe: have you find solution for sabre web service ? PinmemberElmue19-Jun-12 5:58 
QuestionWhat about WSDL?? Pinmemberdevelopertest110-Mar-10 20:07 
AnswerRe: What about WSDL?? PinmvpElmue11-Mar-10 3:03 
Generalhelp- parse error Pinmemberbmnot22-Feb-10 20:09 
GeneralRe: help- parse error PinmvpElmue23-Feb-10 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 27 Aug 2009
Article Copyright 2009 by Elmue
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid