In both previous tutorials, I am talking about basics. How you can set up PHP web service or REST API development setup, basic REST API call, etc. In this tutorial, I am going to share with you how you can connect to the database, execute queries, and get results in JSON format in RESTful API. So without wasting time let's start our study.
I am using XAMPP localhost server. So make sure you have created a database using PHPMyAdmin. Here my database name is logindetail.
Constants.php file code as below
Body as shown in the following picture. content-type application/json should be in the header section
How to develop php web service part 1:Basic set-up for development
For making our development accessible, Manageable, and organize, our database connection should be in a separate file. Since I am going to create a simple user registration and login web service. So for my connivance, I have created a folder which name is include where I keep all necessary PHP files. In include folder, I have created DbConnect PHP class, DbOperation PHP class, PassHash, and Constants PHP file.
I am using XAMPP localhost server. So make sure you have created a database using PHPMyAdmin. Here my database name is logindetail.
//Constants.php file
<?php
//Constants to connect with the database
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'logindetail');
define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
?>
DbConnect.php code as below
<?php
class DbConnect {
private $conn;
function __construct() {}
/**
Establishing database connection
@return database connection handler
*/
function connect() {
//include_once dirname(__FILE__) . './Constants.php';
include_once 'Constants.php'; // we can use above code also
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// returing connection resource
return $this->conn;
}
}
?>
PassHash.php code as below
<?php
class PassHash {
// blowfish
private static $algo = '$2a';
// cost parameter
private static $cost = '$10';
// mainly for internal use
public static function unique_salt() {
return substr(sha1(mt_rand()), 0, 22);
}
// this will be used to generate a hash
public static function hash($password) {
return crypt($password, self::$algo .
self::$cost .
'$' . self::unique_salt());
}
// this will be used to compare a password against a hash
public static function check_password($hash, $password) { //first from db second from user
$full_salt = substr($hash, 0, 29);
$new_hash = crypt($password, $full_salt);
return ($hash == $new_hash);
//$new_hash = crypt($password, $full_salt);
//echo $new_hash;
//return ($new_hash_pass == $password);
}
}
In index.php file write login and registration web service call as below
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require '../include/Constants.php';
require '../include/DbOperation.php';
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;]
});
//this method will create a student ['settings' => ['displayErrorDetails' => true]]
//the first parameter is the URL address that will be added at last to the root url
//The method is post
$app->post('/register', function (Request $request, Response $response) use ($app) {
//Creating a response array
$response = array();
//reading post parameters
$parms = $request->getParsedBody();
$password = $parms['password'];
$email = $parms['email'];
$name = $parms['name'];
//Creating a DbOperation object
require '../include/DbConnect.php';
$db = new DbOperation();
$res = $db->createUser($name, $email, $password);
if ($res == USER_CREATED_SUCCESSFULLY) {
$response["error"] = false;
//$response["message"] = "You are successfully registered";
$response["message"] = $db->getUserByEmail($email);
//echoRespnse(201, $response);
echo json_encode($response);
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Oops! An error occurred while registereing";
//echoRespnse(200, $response);
echo json_encode($response);
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Sorry, this email already existed";
//echoRespnse(200, $response);
echo json_encode($response);
}]
});
$app->post('/login', function(Request $request, Response $response)use($app) {
//Creating a response array
$response = array();
//reading post parameters
$parms = $request->getParsedBody();
$email = $parms['email'];
$password = $parms['password'];
require '../include/DbConnect.php';
$db = new DbOperation();
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['message'] = $user;
echo json_encode($response);
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
echo json_encode($response);
}
} else {
// user credentials are wrong
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
echo json_encode($response);
}
});
$app->run();
?>
for testing this code, You have to use a rest client. I am using insomnia REST Client. You can also use POSTMAN for this. You can call above code by the following URL
registration URL
http://localhost/webAppTest/V1/register
Body as shown in the following picture. content-type application/json should be in the header section
Request
{"name":"sumit","email":"haha3@gmail.com","password":"1234","contactNumber":"1234567890","fcmToken":"","profilePic":""}
response is
{"error":false,"message":{"custid":21,"fname":"sumit","lname":"","email":"haha3@gmail.com","password":"$2a$10$c6492d7fd75d99e20ac4eupNGdmm.2pCezasujv8z2nFdcoCRPDlq",
"mobileno":"","profile_img":"\"\"","state":null,"city":null,"address":null}}
login URL
http://localhost/webAppTest/V1/login
Body as shown in the following picture. using above register JSON data for login
Request
{"name":"sumit","email":"haha3@gmail.com","password":"1234","contactNumber":"1234567890","fcmToken":"","profilePic":""}
Response is
{"error":false,"message":{"custid":21,"fname":"sumit","lname":"","email":"haha3@gmail.com","password":"$2a$10$c6492d7fd75d99e20ac4eupNGdmm.2pCezasujv8z2nFdcoCRPDlq",
"mobileno":"","profile_img":"\"\"","state":null,"city":null,"address":null}}
Next tutorial about how to consume these JSON data and send a JSON data as a request to REST API from the PHP website.
No comments:
Post a Comment