Webservices in PHP (How to create user registration/signup Webservice)
What is Webservices?
Webservices are used to allow users to access data from different sources like the Android app, IOS app, website etc from a centralized database.
We can create a web service through two methods :
- SOAP (Simple Object Access Protocol)
- REST (Representational State Transfer)
SOAP (Simple Object Access Protocol)
SOAP : Simple Object Access Protocol. SOAP is easy to read because SOAP based on XML. SOAP is the XML based format for sending and receiving data.
REST (Representational State Transfer)
REST : Representational State Transfer. It is an architectural style that run over HTTP. REST webservices generate status code response in JSON & XML.
REST support all HTTP methods GET, POST, PUT & DELETE.
GET : Retrieve particular resources by an id
POST : Create a new resource.
PUT : Update a particular resource by an id.
DELETE : Remove a particular resource.
Example of POST
Step 1 : Create a database ( create database your_databasename)
Step 2 : create a SQL table signup. signup table structure given below :
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE `signup` ( `id` int(11) NOT NULL, `fullName` varchar(120) DEFAULT NULL, `gender` varchar(100) DEFAULT NULL, `contactNumber` char(10) DEFAULT NULL, `email` varchar(150) DEFAULT NULL, `password` varchar(200) DEFAULT NULL, `regDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `signup` ADD PRIMARY KEY (`id`); |
Step 3 : Create a database connection file (config.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php // DB credentials. define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PASS',''); define('DB_NAME','database Name'); // put you database name here // Establish database connection. try { $dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")); } catch (PDOException $e) { exit("Error: " . $e->getMessage()); } ?> |
Step 4 : Create a requested url (http://localhost/ws/signup.php)
Signup.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?php include_once("config.php"); header("Content-type:application/json"); $jsdata=json_decode(file_get_contents('php://input'),true); $fname=$jsdata['fullName']; $gender=$jsdata['gender']; $contactno=$jsdata['number']; $email=$jsdata['email']; $password=$jsdata['password']; //Checking email availabilty $sql ="SELECT id FROM signup WHERE email=:email"; $query= $dbh -> prepare($sql); $query-> bindParam(':email', $email, PDO::PARAM_STR); $query-> execute(); $results = $query -> fetchAll(PDO::FETCH_OBJ); if($query -> rowCount() > 0) { header("HTTP/1.1 400 Bad Request"); header('Content-Type: text/plain'); $msg['StatusCode']="205"; $msg['StatusDescription']="Email id already exist. Please try with diffrent email."; print(json_encode($msg)); } else{ $sql="INSERT INTO signup(fullName,gender,contactNumber,email,password) VALUES(:fname,:gender,:contactno,:email,:pasword)"; $query = $dbh->prepare($sql); $query->bindParam(':fname',$fname,PDO::PARAM_STR); $query->bindParam(':gender',$gender,PDO::PARAM_STR); $query->bindParam(':contactno',$contactno,PDO::PARAM_STR); $query->bindParam(':email',$email,PDO::PARAM_STR); $query->bindParam(':pasword',$password,PDO::PARAM_STR); $query->execute(); $lastInsertId = $dbh->lastInsertId(); if($lastInsertId) { header("HTTP/1.1 200 OK"); header('Content-Type: text/plain'); $data=array("StatusCode"=>"200","StatusDescription"=>"Registration successful"); echo json_encode($data); } else { header("HTTP/1.1 400 Bad Request"); header('Content-Type: text/plain'); $msg['StatusCode']="400"; $msg['StatusDescription']="Something went wrong. Please try again."; print(json_encode($msg)); } } |
header(“Content-type:application/json”) sends the http json header to the browser to inform him what the kind of a data he expects.
json_decode(file_get_contents(‘php://input’),true) receive the RAW post data via the php://input IO stream.
We retrieve the raw POST data from the php://input stream.
header(….) detect http response line.
header(“HTTP/1.1 200 OK”); // for successful attempt
header(“HTTP/1.1 400 Bad Request”); // for bad request
header(‘Content-Type: text/plain’) indicates that the content is plain text and no special software is required to read the contents.
How to test this service in your local system
- Install postman chrome extension
- Run postman chrome extension then a new request
- Choose http request method
- Enter the requested url
- Provide the requested data in JSON Format
- Hit the send button
Input parameters will be like this
{
“fullName”: “John Doe”,
“gender”:”Male”,
“number”:”7556645345342″,
“email”:”john@anc.com”,
“password”: “Demo”
}
Output will be in JSON format
For successful attempt
{“StatusCode”:”200″,”StatusDescription”:”Registration successful”}
For unsuccessful attempt
Case 1
{“StatusCode”:”205″,”StatusDescription”:”Email id already exist. Please try with diffrent email.”}
Case 2
{“StatusCode”:”400″,”StatusDescription”:”Something went wrong. Please try again.}
WebSerivces in PHP(Download Source Code)Size: 2.13 KBVersion: V1.1
How to run this script
1. Download and Unzip file on your local system.
2. Put this file inside root directory
3. Database Configuration
Database Configuration
Open phpmyadmin
Create Database webservices
Import database signup.sql (available inside zip package)
requested url for service http://localhost/ws/signup.php
After that use postman chrome extension to hit the WebService.
How to use postman to hit the Webservice