How to Create Web Service in PHP

There are two types of web service which are used, SOAP and REST.
SOAP is Simple Object Access Protocol.  These webservices are XML-based and communicate over HTTP protocol. These are platform independent webservice, so the programmer need not have to worry about the programming language.

RESTful (Representation State Transfer)  webservices are easy to manage and highly scalable web services. These are also platform independent webservices but it supports various data formats like text, json, xml, html.

Today we are going to create simple RESTful webservice in PHP to create new user and get existing user details.

We will be using WAMP server for our developments.

Our MySQL USERS_DATA table will be as below

USERIDUSERNAMECONTACTNOEMAILIDADDRESS
1niks9198000000niks@dummy.comMumbai
2abby9199000000abby@dummy.comDelhi
3mak9197000000mak@dummy.comPune

First we will handle the database related functionality, that is connecting and disconnecting from the database.

1. conn.php – Connecting to database

Add database details as per your setup

<?php
 $username = "username";
 $password = "password";
 $hostname = "localhost";
 $database = "dbname";

//connection to the database
 $dbhandle = mysqli_connect($hostname, $username, $password, $database) 
  or die("Unable to connect to MySQL Database"); 
?>

2. connclose.php – Disconneting from the database
<?php
 //close the connection
 mysqli_close($dbhandle);
 ?>

3. user.php

In this file we are going to write User class with two function to create new user and get existing user details.

<?php  
	class User
	{  
		public function createUser($username,$contactno,$emailid,$address) 
		{
			//Connecting to db  
			include ('conn.php');

			$usersid = '';
			$sqlcount = 'select count(1)+1 usercount from USERS_DATA';
			$result = mysqli_query($dbhandle, $sqlcount);
			while($row1 = mysqli_fetch_array($result))
			{
				$usersid = $row1{'usercount'};
			}

			$sqlinsert = "insert into USERS_DATA (userid,username,contactno,emailid,address) values ('".$usersid."','".$username."','".$contactno."','".$emailid."','".$address."')";
			$result1 = mysqli_query($dbhandle, $sqlinsert);

			//Closing db connection
			include('connclose.php');

			//Return the created userid
			return $usersid;
		}

		
		public function getUserDetails($userid)
		{
			//Connecting to db
			include ('conn.php');
			
			$userdata = '';
			$selectsql = "select username,contactno,emailid,address from USERS_DATA where userid = '".$userid."'";
			$result = mysqli_query($dbhandle, $selectsql);
			while($row = mysqli_fetch_array($result))
			{
				$userdata = $row{'username'}."|".$row{'contactno'}."|".$row{'emailid'}."|".$row{'address'};
			}

			//Closing db connection
			include('connclose.php');

			//Return the user data
			return $userdata;
		}
	}
?>

4. userwebservice.php

Now the last file which will be used for calling the webservice.

<?php
	header('Content-Type: application/json');
	$resultarray = array(); 
	require_once('user.php');
	$User = new User();

	if($_SERVER['REQUEST_METHOD'] == "GET")
	{
		if(isset($_GET['func']))
		{
			if($_GET['func'] == "GET")
			{
				if(isset($_GET['userid']))
				{
					$userdata = $User->getUserDetails($_GET['userid']);
					if($userdata == '')
					{
						$resultarray['result'] = "Error";
						$resultarray['error'] = "User does not exist";
						$resultarray['username'] = '';
						$resultarray['contactno'] = '';
						$resultarray['emailid'] = '';
						$resultarray['address'] = '';
					}else{
						$resultarray['result'] = "Success";
						$resultarray['username'] = explode("|",$userdata)[0];
						$resultarray['contactno'] = explode("|",$userdata)[1];
						$resultarray['emailid'] = explode("|",$userdata)[2];
						$resultarray['address'] = explode("|",$userdata)[3];
					}
				}else{
					$resultarray['result'] = "Error";
					$resultarray['error'] = "User id required";
				}
			}
			
			
			if($_GET['func'] == "CREATE")
			{
				if(isset($_GET['username']) && isset($_GET['contactno']) && isset($_GET['emailid']) && isset($_GET['address']))
				{
					$userid = $User->createUser($_GET['username'],$_GET['contactno'],$_GET['emailid'],$_GET['address']);
					
					if($userid == '')
					{
						$resultarray['result'] = "Error";
						$resultarray['error'] = "Unable to Create User id";
						$resultarray['userid'] = '';
					}else{
						$resultarray['result'] = "Success";
						$resultarray['userid'] = $userid;
					}
				}else{
					$resultarray['result'] = "Error";
					$resultarray['error'] = "All the details are mandatory for creating new User";
				}
			}
		}else{
			$resultarray['result'] = "Error";
			$resultarray['error'] = "Functionality is Required";
		}
	}else{
		$resultarray['result'] = "Error";
		$resultarray['error'] = "Invalid Request Method";
	}

	echo json_encode($resultarray);
?>

Finally create a folder “PHPWebServiceDemo” in www folder in WAMP directory and put all the above files in it and start server.

Now as everything is set, lets test it out!
We are going to use Boomerang SOAP & REST Client, a Google Chrome plugin for testing. Install and open the plugin. Click on Create Service -> Select REST -> Enter Service Name

Select GET method

Enter endpoint URL as http://localhost:9000/PHPWebServiceDemo/userwebservice.php

If you have created folder in www of WAMP directory with different name then use that name instead of PHPWebServiceDemo in above URL

Go to Params and enter input parameters as below

And click on Send. You will get response as below

Similarly for adding new user pass input parameters as below (we are not passing userid as input while creating new user as it will be created by service and returned as output)

And the response