IDIOT DEVELOPER

Creating Web Services in PHP
Creating Web Services in PHP
DOWNLOAD

Web services is a standardized way or medium to propagate communication between the client and server applications on the World Wide Web. A web service is any piece of software that makes itself available over the internet which takes request from the client and give responses to the requests that the server received from the client. In a Web service, HTTP protocol is used for communication and response is generated to client in XML or JSON format.

 

Today in this tutorial we are going to create our own web services,  way web services can be created in any language like Java, .NET, or any other language. But for this tutorial we are going to use PHP and MySQL. The final output or responses will be generated in JSON format.

 

As we are using PHP and MySQL, so first we need a database connection. For Database connection we are going to use PDO (PHP Data Object). If you dont know what is PDO then read my tutorial on PDO.

 

config.php

 


<?php

define('HOST', 'localhost');
define('DBNAME', 'fb');
define('USERNAME', 'root');
define('PASSWORD', '');

define('KEY', '123456');

function get_db(){
  try{
    $conn = new PDO('mysql:host='.HOST.'; dbname='. DBNAME, USERNAME, PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $conn;
  }catch(PDOExecption $e){
    die("Error: " . $e->getMessage());
  }
}

?>

 

Next we are going to create a simple service which is going to return the user information according to User Id given by the client. As we are working on a web service all our parameter we require we get via URL. We will check each parameter in the URL and if any error or problem is found we will return an error.

 

First of all we will include config.php file and get the database connection.

 


include('config.php');
$conn = get_db();

 

After that we will  sends the http json header to the browser to inform him what the kind of a data he expects. You can see all the http headers for each request in your browser (If you are using chrome open developer tools, go to network, adjust the view and reload the page, you will see all requests made by your browser, if you click on any on any of these requests then click on headers you will see the headers of each request).

 


header("Content-Type:application/json");

 

Then we will create a function that will return the data to each request in JSON format.

 


function respond($status, $msg, $data){
  header("HTTP/1.1 $status $msg");
  $resp['status'] = $status;
  $resp['msg'] = $msg;
  $resp['data'] = $data;
  echo json_encode($resp);
}

 

As information of a user is very sensitive data we cannot provide to everyone, so to make sure that the information is in the right hand, we have a KEY. The URL or the client which provides the correct key will be given the information.

 


if( !isset($_REQUEST['key']) || trim($_REQUEST['key']) != KEY ){
  respond("201", "Invalid Key Value.", NULL);
  die();
}

 

Then we will check what kind of information the client whats to take, for that we have an action parameter in the URL. This action parameter will determine what kind of information the client whats. i have only made one service i.e. userinfo – this provide general user information. You can make more services.

 


if(!isset($_REQUEST['action'])){
  respond("201", "Please provide action parameter value in URL.", NULL);
  die();
}

$action = trim($_REQUEST['action']);

 

If a specific service requires parameter that will be given using the URL. Each parameter is checked. If the parameter(s) are valid then only the program continues. If no error is found during finding the data required by the client, the the data is given to the client. Otherwise an error is returned.

 


if($action == 'userinfo'){
  if( !isset($_REQUEST['uid']) ){
    respond("201", "Invalid uid(User Id)", NULL);
    die();
  }

  $uid = $_REQUEST['uid'];
  $stmt = $conn->prepare("SELECT fname, lname, email FROM user WHERE uid = $uid");
  $stmt->execute();

  if($stmt->rowCount() <= 0){
    respond("201", "Invalid uid(User Id)", NULL);
  }else{
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $data = $stmt->fetch();
    respond("200", "Success", $data);
  }

} else{
  respond("201", "No Service Found", NULL);
}

 

How to use

 


SITE_URL/service.php?key=123456&action=userinfo&uid=1

Leave a Reply

Your email address will not be published. Required fields are marked *