Php Webservice

25
 Build a Web service with PHP Learn how to create integrated Web applications with SOAP Skill Level: Intermediate Tyler Anderson ( [email protected]) Engineer Stexar Corp. 23 May 2006 In the past few years, new Web services have been popping up all over the Internet. And what better language to build your own Web service in than PHP? With PHP, you have the advantage of a great scripting language with the power to connect to databases, an easy development curve that allows for faster development, and high response times -- thanks to the underlying libraries compiled for performance. Section 1. Before you start About this tutorial This tutorial is for PHP programmers that would like to jump on the Web services bandwagon by creating a Web service in PHP. You'll build a Web service by building a SOAP server in PHP. The Web service you will create will be a vehicle lookup service that takes in queries based on make, model, and year. The Web service will then query an internal database and respond appropriately. A Web-based client will also be coded in PHP to communicate and query the SOAP server. It creates a chain of three SOAP servers in PHP. In reality, each of the three servers would be placed in three different physical locations or cities where a chain of car dealerships would coexist. The client would then be hosted at one location where car customers would come and visit, enteri ng search queries to find the vehic les of their dreams . The client routes the query to each of the three SOAP servers, which, in turn, send Build a Web service with PHP  © Copyright IBM Corporation 1994, 2008. All rights reserved.  Page 1 of 25

description

Tutorial Webservice using PHP programming

Transcript of Php Webservice

  • Build a Web service with PHPLearn how to create integrated Web applications with SOAP

    Skill Level: Intermediate

    Tyler Anderson ([email protected])EngineerStexar Corp.

    23 May 2006

    In the past few years, new Web services have been popping up all over the Internet.And what better language to build your own Web service in than PHP? With PHP,you have the advantage of a great scripting language with the power to connect todatabases, an easy development curve that allows for faster development, and highresponse times -- thanks to the underlying libraries compiled for performance.

    Section 1. Before you start

    About this tutorialThis tutorial is for PHP programmers that would like to jump on the Web servicesbandwagon by creating a Web service in PHP. You'll build a Web service by buildinga SOAP server in PHP. The Web service you will create will be a vehicle lookupservice that takes in queries based on make, model, and year. The Web service willthen query an internal database and respond appropriately. A Web-based client willalso be coded in PHP to communicate and query the SOAP server. It creates achain of three SOAP servers in PHP. In reality, each of the three servers would beplaced in three different physical locations or cities where a chain of car dealershipswould coexist. The client would then be hosted at one location where car customerswould come and visit, entering search queries to find the vehicles of their dreams.The client routes the query to each of the three SOAP servers, which, in turn, send

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 25

  • results back to the client. Upon receiving each response, the client displays thesearch results to the user for analysis.

    System requirementsThe following tools are needed to follow along:

    Web serverAny operating system and any Web server can be used. Feel free to useApache V2.X, or IBM's HTTP Server; download from Apache or from IBM.

    PHPDue to the use of PHP data objects, PHP V5.1 or later is required. Be sure toconfigure with the following option to include support for Derby and the SOAPextensions: --with-pdo-odbc=ibm-db2,/home/db2inst1/sqllib--enable-soap. See Resources for information about configuring Apache orIBM's HTTP Server with PHP.

    DatabaseThis tutorial uses Apache Derby, which is open source and lightweight. Alsodownload the IBM DB2 JDBC Universal Driver and the DB2 Run-Time Client.Make sure to set your CLASSPATH appropriately by following the instructionson each page. You can follow the Linux or Windows instructions forinstalling and downloading the DB2 Run-Time Client. See Resources for moreinformation to help you get the configuration right.IBM Cloudscape may also be used for this tutorial. The internals of it are thesame as Derby; however, the DB2 JDBC Universal Driver and other things arepackaged into Cloudscape, and it is supported by IBM. Download IBMCloudscape V10.1 and the DB2 Run-Time Client from IBM.

    Java technologyDerby requires Java technology. Download from Sun Microsystems or fromIBM.

    Section 2. Overview and setting up

    Web services have been a hit for some time now, and the popularity just keepsgrowing. But why? It's because they are the perfect way to integrate several entitiesinto one, allowing for better flow of information to management and to customers.

    PHP is definitely not behind in this area. Being one of the fastest-growing languages,

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 2 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • PHP commands a host of developers that require this technology, too. Take a lookat the technology behind Web services, SOAP, and how databases like Derby helpenable a more powerful Web service.

    SOAPWhat does SOAP mean? It stands for Simple Object Access Protocol, and it'sessentially a standard for exchanging XML-based data via HTTP. In other words: It'sthe signal that goes down the telephone lines if you were talking with your friend onthe phone, but instead of you and your friend talking on the phone, it'll be carcustomers searching for the vehicles of their dreams in a chain of car dealerships.An example of a SOAP message is shown in Listing 1.

    Listing 1. A SOAP message

    SOAP-ENV:ServerBad Request. Can't find

    HTTP_RAW_POST_DATA

    While you'll see this again later, it's shown here so you can get a feel for thetechnology. The body of most SOAP messages has data, similar to the fault shownhere. Sometimes a header is used to hold encryption and other context-sensitivedata for the SOAP construct being sent. Also, SOAP messages are sent as raw XMLdata.

    How databases fit inA Web service can hardly be useful without a database. You can use a database tostore information about what a particular user queried or looked at during a visit.Most existing systems of large companies have a vast array of databases andinformation, making the use of databases vital for a successful Web service -- evenfor established Web sites.

    Site information is almost always stored in a database, and accessing suchinformation via a Web service is just as important. So learning how to integrate yourPHP Web service with a database is vital, just as it is with the basic PHP setup. PHPdevelopment just isn't PHP development without a database ready at your beck andcall.

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 25

  • The example dealership application in PHPIn this tutorial, you'll take advantage of all the above for your Web service, enablingyou to get a jumpstart into your own PHP Web service development. The applicationyou're going to build has a user interface where users can enter queries, as shownbelow.

    Figure 1. Searching for the vehicle of your dreams

    Section 3. Simple SOAP server in PHP

    You'll create a simple SOAP server to learn to use basic PHP SOAP servercapabilities. This section will give you a taste of and prepare you for the rest of thetutorial.

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 4 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • Creating a serverA simple server takes a SOAP request and returns a response. Create a simpleecho application that takes in a string and sends it back with the word ECHO tackedonto the front. Create a file called simple_server.php, and define it as shown below.

    Listing 2. A simple SOAP server

    The first item is the echoo function. It returns the string passed to it and appendsECHO: to the front of it. Also, see how the SoapServer object is created in PHP.Then add the echoo function to the list of functions that the SOAP server supports.You have to call the function echoo because echo is a reserved word in PHP,similar to the print command. The last line calls the handle method of theSoapServer object, allowing the server to handle the SOAP request and return aresponse, as defined in the echoo method.

    SOAP messagesPointing a browser to your SOAP server in its current status causes a fault becauseof the way the request is sent. The data needs to be sent as raw POST data viaHTTP, as described by the faultstring.

    Listing 3. Pointing a browser to the SOAP server

    SOAP-ENV:ServerBad Request. Can't find

    HTTP_RAW_POST_DATA

    Your server is now live, but you can only access it via a SOAP client or you'll get

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 25

  • fault errors, as shown above. Now that you know the SOAP server is working, youcan move onto creating a simple client.

    Creating a client: Echo formA client allows you to send data to the SOAP server using the correct expectedprotocol. Since all you need is any string to send to the SOAP server to test it out,you'll create a simple form with one text box and a button. Create a file calledsimple_client.php and define it, as shown below.

    Listing 4. Creating a simple form

  • Creating a client: Making the requestOnce the button is clicked, the text in the text box, shown above, gets sent to thePHP script in the URL, which you can extract in the GET array. This allows you toverify that a request was sent and process it. Continue defining thesimple_client.php file, as shown below.

    Listing 5. Handling requests and sending them to the SOAP server

    ...

    print "";

    if($echo != ''){$client = new SoapClient(null, array('location' => "http://localhost/soap/simple_server.php",'uri' => "urn://tyler/req"));

    $result = $client->__soapCall("echoo",array($echo));

    print $result;}?>

    Now if $echo has data in it, something was entered in the text box, and a requestwas made. This allows you to initiate the request to the SOAP server by creating theSoapClient object. The client knows where to send requests by the location in theparameters array. The uri gives the SOAP packet a namespace, which is

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 25

  • essentially a context. Once the SoapClient is initialized, make the request to theSOAP server by calling the client's __soapCall method with two parameters: themethod in the SOAP server you wish to call and an array of parameters. Then youdisplay the response sent from the SOAP server underneath the GO button, whichyou can preview below.

    Figure 3. Displaying the response from the SOAP server

    There you have it. You can even see the value of the input text box in the URL. Nowthat you've created a simple SOAP server, you'll create a more complex one thatuses Apache Derby and multiple SOAP servers.

    Section 4. Derby: Setting up

    Derby's a great database for this application because it's lightweight and easy touse. The application in this tutorial uses it to search for vehicles matching the searchcriteria, and this section sets everything up, so you're good to go.

    Creating the databaseSince PHP connects to Derby using the network server and ODBC, start the serverby typing:

    javaorg.apache.derby.drda.NetworkServerControl

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 8 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • start

    When the application starts, it's ready to accept connections. Connect to and createa new database using the Derby ij tool:

    java org.apache.derby.tools.ij

    You should now be at the ij prompt, where you can enter database commands.The ij tool allows you to create and connect to databases, as well as query them asyou would in PHP. This helps you fine-tune and perfect your search queries beforeimplementing them in your PHP application. Now you'll create and connect to thedatabase:

    connect'jdbc:derby:net://localhost:1527/DEALER;create=true:user=dealer;password=dealer;';

    Here, you've created the DEALER database with user and password being dealer.Next, you'll catalog the database in DB2 so the PHP ODBC drivers will see our newdatabase and be able to connect to it.

    Cataloging the database in DB2Start the DB2 client: In Linux, type db2 at the command line; in Windows, click onthe Command Line Processor application installed under Programs > IBM DB2 >Command Line Tools. When you have the DB2 prompt up, type the following:

    catalog tcpip node cns remote localhost server 1527

    This creates a node you'll catalog the database to:

    catalog db DEALER at node cns authentication server

    Our DEALER database is now associated with the cns node. Next, catalog theDEALER database as a system ODBC data source so the PHP ODBC drivers willfind and recognize the DEALER database:

    catalog system odbc data source DEALER

    The DEALER database is ready to go! You could connect to it in PHP, but beforeyou do, learn more about its purpose and initialize it with tables.

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 25

  • The DEALER databaseThis database holds three tables -- one for each physical dealership location. Eachlocation will have its own table in the database with vehicle data. And when queriesfrom the SOAP client come to the SOAP server, each SOAP server will query itsown database table and return the results for it. The three tables:

    vehicles_steinbach

    vehicles_pinefalls

    vehicles_selkirk

    Each table contains the vehicles for each of three cities, which you'll create next.

    Creating the vehicle tables for each locationCreate each of the three tables for the dealership application using the ij tool.Create them using the SQL commands at the ij prompt, as shown below.

    Listing 6. Create the three tables

    drop table vehicles_steinbach;create table vehicles_steinbach (make varchar(50),

    model varchar(50),yyear varchar(4),price integer,feature_desc varchar(512));

    drop table vehicles_pinefalls;create table vehicles_pinefalls (make varchar(50),

    model varchar(50),yyear varchar(4),price integer,feature_desc varchar(512));

    drop table vehicles_selkirk;create table vehicles_selkirk (make varchar(50),

    model varchar(50),yyear varchar(4),price integer,feature_desc varchar(512));

    Each table has a make, model, yyear, price, and feature_desc describing avehicle's features.

    The database skeleton is complete with the creation of these tables. Now let's fill inthe guts by adding some content to the database.

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 10 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • Initializing each table with vehicle informationMost dealerships -- even chains -- customize each dealership to a certain make, etc.You'll see this in the choices for the contents of each table. Use the following SQL,shown below, or create content of your own as the content of the database.

    Listing 7. Filling in the three tables with content

    insert into vehicles_steinbach values('Chrysler', 'Crossfire', '2005', 19999,

    'Air conditioning, power windows'),('Chrysler', 'Sebring', '2003', 14999, 'Convertible'),('Dodge', 'Viper', '2006', 89999, 'loaded'),('Chrysler', '300', '2003', 18999, 'Leather seats'),('Dodge', 'Durango', '2004', 23999, 'Supercharged engine');

    insert into vehicles_pinefalls values('Toyota', 'Camry', '2001', 13999, 'Power steering'),('Toyota', 'Tacoma', '2002', 16999, 'Power seats'),('Lexus', 'LS', '2003', 26999, 'Built in GPS'),('Toyota', 'Prius', '2004', 29999, 'Built in TV and DVD player'),('Lexus', 'GS', '2005', 34999, '10 CD changer');

    insert into vehicles_selkirk values('Saturn', 'Vue', '2004', 15999, 'Power locks'),('Saturn', 'Ion', '2005', 12499, 'Reliable'),('Saturn', 'Sky', '2006', 19999, 'Convertible, must see!'),('Saturn', 'Relay', '2004', 14999, 'Very roomy'),('Saturn', 'L300', '2001', 9999, 'Chrome wheels');

    Your database is finished and ready to be queried by your PHP application, whichyou'll begin architecting next.

    Section 5. Architecting the user interface

    With the database ready to go, you can begin work on the PHP application. By theend of this section, your application will have a user interface complete with a formthat takes in the make, model, and year of the vehicle being searched for.

    The headerWhen a page is requested, the header appears at the top of the page, and placingthose contents in a separate PHP script makes your code modular and easier toread because you can simply include the header file at the top of a new scriptwithout it cluttering the file. Create a header.php file and define it, as shown below.

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 25

  • Listing 8. Creating a header file

  • Looking up vehicles with a formWith the header and footer created, you can focus on the main content of the userinterface for your application. Create a file called index.php and define it, as shownbelow.

    Listing 10. Creating the form used to search for vehicles

  • The code for the form is in bold to make it easier for you to isolate, since you canformat the rest however you want. Like the Echo form, the HTTP transfer method ofthis form is via GET because there will be no database or other side-effects causedby executing this query. Once the query is executing, the action field specifies thatthe form should send the data to this same index.php script. The first three lines ofthe script retrieve the data from the URL or GET array, which you'll process next.Before you go there, however, you can preview the form.

    Figure 5. Searching for vehicles

    Processing the form and calling the clientOnce a request has been made by a car customer, your code needs to handle thatrequest and call client code to request responses from each of the three SOAPservers. Do so by completing the index.php file, as shown below.

    Listing 11. Handling requests from the user interface

    print "";print "";

    if($_GET['submit'] === 'GO' &&($make != '' || $model != '' || $year != '')){print "Search Results:";require('client.php');

    }

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 14 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • require('footer.php');?>

    You'll know that the request has been made by a car customer if the GET array'ssubmit value equals GO. Now if the button got clicked and any one or more of thetext boxes was filled in, initialize a request to the SOAP servers via the client code,which you'll define in the next section.

    Now you'll create a simple Web server for each of the three locations, in preparationto test the client code you'll develop in the next section.

    Simple Web services for each locationStart with a simplified version of the Web service and build on it later. Create threefiles: server_steinbach.php, server_pinefalls.php, and server_selkirk.php, and defineeach of them, as shown below.

    Listing 12. Creating the three SOAP servers

    Notice that the vehicleLookup method is what the client code will call in passingthe vehicle search query to the SOAP servers.

    Great! Your application framework is ready for the client code.

    Section 6. The client

    Client code is usually referred to as code that creates a client capable ofcommunicating with a server, sends a request, and receives a response. That's whatyou'll develop in this section: code that creates clients to communicate with each ofthe three dealership locations.

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 25

  • Initializing a client for each locationThe first step in sending requests to the SOAP servers is creating three clients withtheir locations set to point to each of the three URLs of the three SOAP servers.Create a file called client.php and define it, as shown below.

    Listing 13. Create three SOAP clients

  • Notice how each response for each call to each client's __soapCall is stored. The__soapCall method accepts two parameters you're interested in. The first is thename of the method in the SOAP server you're calling and the other is the array ofparameters you're passing.

    Displaying resultsNow that you've got results, you can display them. Finish defining the client.php file,as shown below.

    Listing 15. Displaying search results to the car customer

    ...

    $result_selkirk = $client_selkirk->__soapCall("vehicleLookup",array($make,$model,$year));

    if($result_steinbach != '' ||$result_pinefalls != '' ||$result_selkirk != ''){print "";print

    "MakeModel";

    print "Year";print

    "PriceDescription";

    print $result_steinbach;print $result_pinefalls;print $result_selkirk;print "";

    }?>

    If one of the three dealerships (SOAP servers) returns results, display the table, withthe results from each of the three dealerships as rows. Preview current resultsbelow.

    Figure 6. Search results

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 25

  • When you finish defining the server in the next section, the output will displayresults, rather than just echo.

    Section 7. The server

    Now you'll develop the SOAP server. The three SOAP servers get called by theclient code, and each of them returns results, as found in their own local databases.In this section, you'll develop the server by connecting to and querying the Derbydatabase, and returning formatted results.

    Connecting to Derby

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 18 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • Before the database can be queried, you need to connect to it in PHP. Define ahandy db_connect function in all three sever files, as shown below.

    Listing 16. Connecting to the DEALER database

  • ...

    First you retrieve the PHP data object from connecting to the database. Then youcheck each of the three parameters to see if they have contents (meaning that theyare not equal to the null string). If they do, append them to the $query string, whichyou'll use in the where clause of the SQL statement. The code needed for $make iseasy and gets slightly more complex with $model and $year. For the latter twocases, if $query and the parameter aren't empty, append them to the where clausewith and as the suffix. Otherwise, if the parameter isn't empty, set it to $query, anddo nothing if both $query and the parameter are empty. Finally, create the SQLstatement by selecting from the table, inserting $query as the value for the whereclause.

    Querying the database and formatting resultsNow that the SQL statement is prepared and ready for use in querying the database,you'll query the database, as shown below.

    Listing 18. Querying the database and formatting results

    ...

    $sql = "select * from ".TABLE." where $query";

    $ret = '';foreach($pdo->query($sql) as $row){

    $make = $row['MAKE'];$model = $row['MODEL'];$year = $row['YYEAR'];$price = $row['PRICE'];$desc = $row['FEATURE_DESC'];$ret .= "$make";$ret .= "$model";$ret .= "$year";$ret .= "$price";$ret .= "$desc";

    }return $ret;

    }

    Set up the return parameter, $ret, by setting it to the null string, or ''. Then querythe database in the foreach statement and loop through each of the results, whichget stored in $row with each iteration of the loop. The next five statements retrievethe make, model, yyear, price, and description information from thedatabase. The next five statements format these results in a row using HTML. Thelast statement returns the results to the client, which displays them.

    Customizing for each location

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 20 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • Did you notice the use of the TABLE defined in Listing 17? This is what makes eachserver different from one another as each one queries a different table in thedatabase. Finish off each of the server files by adding the code, as shown below.

    Listing 19. Defining the TABLE

  • Excellent! The application's complete, and you're now a PHP SOAP server guru.

    Section 8. Summary

    You've developed a SOAP server in PHP. Now you can do what Amazon andGoogle do with Web services by building integrated Web applications with Webservices in the infamous PHP programming language. To top it off, you've integratedyour Web service with the lightweight capabilities of the Derby database for dataquery and storage.

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 22 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • DownloadsDescription Name Size Download methodSource code os-php-webservice.source.zip5KB HTTP

    Information about download methods

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 25

  • ResourcesLearn

    Explore the differences between the open source Apache Web server andIBM's version in "Hosting PHP applications on the IBM HTTP Server."

    To find out how to get Apache V2 and PHP V4.x (may also use PHP V5.x)working together on Linux, see Apache 2 and PHP Installation.

    To learn how to install and configure PHP on Windows (some steps areapplicable to Linux), read "Connecting PHP Applications to Apache Derby."

    To broaden your PHP skills, check out the "Learning PHP" tutorial series onbuilding a workflow application.

    Learn more about PHP data objects and their capabilities in the PHP Manual. For an excellent resource to learn more about XML namespaces, read XML

    Namespaces Explained. Visit IBM developerWorks' PHP project resources to learn more about PHP. Stay current with developerWorks technical events and webcasts. Check out upcoming conferences, trade shows, webcasts, and other Events

    around the world that are of interest to IBM open source developers. Visit the developerWorks Open source zone for extensive how-to information,

    tools, and project updates to help you develop with open source technologiesand use them with IBM's products.

    To listen to interesting interviews and discussions for software developers, besure to check out developerWorks podcasts.

    Get products and technologies Download Java technology from Sun Microsystems or from IBM. Innovate your next open source development project with IBM trial software,

    available for download or on DVD.Discuss

    Get involved in the developerWorks community by participating indeveloperWorks blogs.

    About the authorTyler Anderson

    developerWorks ibm.com/developerWorks

    Build a Web service with PHPPage 24 of 25 Copyright IBM Corporation 1994, 2008. All rights reserved.

  • Tyler Anderson used to work for DPMG.com, an SEO company, for whom he wroteproprietary SEO software. He graduated with a degree in computer science fromBrigham Young University in 2004 and has just graduated with a master of sciencedegree in computer engineering in 2005, also from Brigham Young University. He iscurrently an engineer for Stexar Corp., based in Beaverton, Ore.

    ibm.com/developerWorks developerWorks

    Build a Web service with PHP Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 25

    Table of ContentsBefore you startAbout this tutorialSystem requirements

    Overview and setting upSOAPHow databases fit inThe example dealership application in PHP

    Simple SOAP server in PHPCreating a serverSOAP messagesCreating a client: Echo formCreating a client: Making the request

    Derby: Setting upCreating the databaseCataloging the database in DB2The DEALER databaseCreating the vehicle tables for each locationInitializing each table with vehicle information

    Architecting the user interfaceThe headerThe footerLooking up vehicles with a formProcessing the form and calling the clientSimple Web services for each location

    The clientInitializing a client for each locationLooking up vehicles from each SOAP serverDisplaying results

    The serverConnecting to DerbyCreating the database queryQuerying the database and formatting resultsCustomizing for each location

    SummaryDownloadsResourcesAbout the author