SlideShare a Scribd company logo
How to Create Login and Registration
API in PHP
In today’s article, we will explore the concept of REST API and delve into
creating a login and registration system using these APIs. In the
contemporary landscape of web development, establishing strong and
secure authentication systems is of utmost significance. A highly effective
approach is to construct a Login and Registration system through the
utilization of REST APIs. This article aims to provide you with a
comprehensive walkthrough, enabling you to construct a robust and
efficient user authentication system from the ground up, harnessing the
capabilities of REST architecture.
What is REST API
REST (Representational State Transfer) APIs act as a bridge between
the client and the server, facilitating effective communication between
them. They utilize HTTP requests to transfer data and are an optimal
choice for constructing systems due to their stateless nature. REST APIs
provide a seamless integration experience across a variety of platforms
and devices.
PHP Login and
Registration REST API
Before we start coding, ensure you have a development environment set
up. Install a web server (e.g., Apache), PHP, and a database (such as
MySQL). Organize your project directory and create separate folders for
PHP files, configurations, and assets.
1. Designing the Database Structure
For REST APIs
DATABASE NAME TABLE NAME
APPWEBRESTAPI USERS
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`full_name` text NOT NULL,
`phone_number` text NOT NULL,
`email_id` text NOT NULL,
`username` text NOT NULL,
`password` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT
current_timestamp(),
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2. Creating Files and Folders For
the Projects
Note: In this tutorial, we are utilizing PDO for all
database operations. If you are interested in learning
about using MySQL or MySQLi, please leave a
comment indicating your preference. I will either update
this tutorial or create a new article on that topic as well.
Creating files and folders for our projects is an essential step in organizing
and managing our code.
How to Create Login and Registration API in PHP.pdf
Configrations.php
<?php
// DEVELOPEMENT SERVER DETAILS ...
$DATABASE_SERVER_IP = "localhost"; // put your
database server host
$DATABASE_USER_NAME = "root"; // put your database
username
$DATABASE_USER_PASSWORD=""; // put your database
password, there is no default password
$DATABASE_NAME="appwebrestapi"; // your database
name
DBConnect.php
<?php
require_once 'configurations.php';
try {
$con = new PDO(
"mysql:host=$DATABASE_SERVER_IP;
dbname=$DATABASE_NAME",
$DATABASE_USER_NAME,
$DATABASE_USER_PASSWORD
);
// set the PDO error mode to exception
$con->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
DOWNLOAD CODE FROM GIT
Implementing User
Registration REST API:
Before implementing registration, it’s essential to understand why we are
using the POST method for the registration.
Using the POST method for login and registration in our APIs with PHP, is
crucial to ensure the security and integrity of sensitive user data. The
POST method offers a secure way to transmit information by sending data
in the HTTP request body, rather than exposing it in the URL. This protects
sensitive information like passwords from accidental exposure through
browser history, bookmarks, or shared links. With its ability to handle larger
and more complex data payloads, the POST method supports the secure
transfer of user credentials and additional registration details. By using
POST, developers can implement essential security measures such as
Cross-Site Request Forgery (CSRF) tokens, process data server-side,
and adhere to best practices, contributing to a robust and secure
authentication process.
<?php
header('Content-type: application/json');
if($_SERVER['REQUEST_METHOD']==='POST'){
$server__response__success = array(
"code"=>http_response_code(200),
"status"=>true,
"message"=>"Request Accepted"
);
echo json_encode($server__response__success);
} else {
http_response_code(404);
$server__response__error = array(
"code"=>http_response_code(404),
"status"=>false,
"message"=>"Bad Request"
);
echo json_encode($server__response__error);
}
Before proceeding further, it is
necessary to explain why I am using
$_SERVER[‘REQUEST_METHOD’].
$_SERVER[‘REQUEST_METHOD’] is a built-in PHP superglobal
variable that holds the HTTP request method used by the client to access
the current script. It provides valuable information about how the request
was made, whether it was through the GET, POST, PUT, DELETE, or other
HTTP methods. Developers often use $_SERVER[‘REQUEST_METHOD’]
to determine the nature of the request and handle different actions
accordingly, such as processing form data, handling API endpoints, or
performing specific server-side operations based on the HTTP method
used. This versatile variable plays a fundamental role in routing and
processing incoming requests in PHP applications.
Here, we are only accepting POST requests. When any other request type
is sent to the server, the API will reject the request and respond with a 404
error to the client.
Example with GET request
Example with POST request
Proceed with the implementation now (Final Code).
<?php
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (
!empty($_POST['fullName']) &&
!empty($_POST['phoneNumber']) &&
!empty($_POST['emailID'])
&& !empty($_POST['userName']) &&
!empty($_POST['userPassword'])
) {
$fullName = $_POST['fullName'];
$phoneNumber = $_POST['phoneNumber'];
$emailID = $_POST['emailID'];
$userName = $_POST['userName'];
$userPassword = $_POST['userPassword'];
try {
require 'DBConnect.php';
// check for duplicate user
// here I am check for user email id for
the same
$SELECT__USER__SQL = "SELECT * FROM
`users` WHERE users.email_id=:emailID;";
$duplicate__user__statement =
$con->prepare($SELECT__USER__SQL);
$duplicate__user__statement->bindParam(':emailID',
$emailID, PDO::PARAM_STR);
$duplicate__user__statement->execute();
$duplicate__user__flag =
$duplicate__user__statement->rowCount();
if ($duplicate__user__flag > 0) {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "This user is already
registered."
);
echo
json_encode($server__response__error);
} else {
// insert/add new user details
// encrypt user password
$password__hash =
password_hash($userPassword, PASSWORD_DEFAULT);
$data__parameters = [
"fullName" => $_POST['fullName'],
"phoneNumber" =>
$_POST['phoneNumber'],
"emailID" => $_POST['emailID'],
"userName" => $_POST['userName'],
"userPassword" => $password__hash
];
// insert data into the database
$SQL__INSERT__QUERY = "INSERT INTO
`users`(
`full_name`,
`phone_number`,
`email_id`,
`username`,
`password`
)
VALUES(
:fullName,
:phoneNumber,
:emailID,
:userName,
:userPassword
);";
$insert__data__statement =
$con->prepare($SQL__INSERT__QUERY);
$insert__data__statement->execute($data__parameters);
$insert__record__flag =
$insert__data__statement->rowCount();
if ($insert__record__flag > 0) {
$server__response__success =
array(
"code" =>
http_response_code(200),
"status" => true,
"message" => "User
successfully created."
);
echo
json_encode($server__response__success);
} else {
http_response_code(404);
$server__response__error = array(
"code" =>
http_response_code(404),
"status" => false,
"message" => "Failed to create
user. Please try again."
);
echo
json_encode($server__response__error);
}
}
} catch (Exception $ex) {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Opps!! Something Went
Wrong! " . $ex->getMessage()
);
echo
json_encode($server__response__error);
} // end of try/catch
} else {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Invalid API parameters!
Please contact the administrator or refer to the
documentation for assistance."
);
echo json_encode($server__response__error);
} // end of Parameters IF Condition
} else {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Bad Request"
);
echo json_encode($server__response__error);
}
In the above code, we are also checking for duplicate
user registration to prevent redundant records from
being entered into the database.
OUTPUT
Thoroughly test your REST API using tools like Postman or cURL.
TEST CASE 1 – With Valid Input
{
"code": 200,
"status": true,
"message": "User successfully created."
}
TEST CASE 2 – With In-valid Input
Copy Code
{
"code": 404,
"status": false,
"message": "This user is already registered."
}
Implementation of User
Login API
Develop another PHP script, Login.php, to handle user login. Validate the
provided login credentials against stored data in the database.
<?php
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!empty($_POST['userName']) &&
!empty($_POST['userPassword'])) {
$userName = $_POST['userName'];
$userPassword = $_POST['userPassword'];
try {
require 'DBConnect.php';
// checking for valid user details
$SELECT__USER__DATA = "SELECT * FROM
`users` WHERE users.username=:userName";
$select__user__statement =
$con->prepare($SELECT__USER__DATA);
$select__user__statement->bindParam(':userName',
$userName, PDO::PARAM_STR);
$select__user__statement->execute();
$user__flag =
$select__user__statement->rowCount();
if ($user__flag > 0) {
$user__data =
$select__user__statement->fetch(PDO::FETCH_ASSOC);
if (password_verify($userPassword,
$user__data['password'])) {
$user__object = array(
"fullName"=>$user__data['full_name'],
"emailID"=>$user__data['email_id'],
"userName"=>$user__data['username']
);
http_response_code(200);
$server__response__success =
array(
"code" =>
http_response_code(200),
"status" => true,
"message" => "User Verified" ,
"userData"=>$user__object
);
echo
json_encode($server__response__success);
} else {
http_response_code(404);
$server__response__error = array(
"code" =>
http_response_code(404),
"status" => false,
"message" => "Opps!! Incorrect
Login Credentials"
);
echo
json_encode($server__response__error);
}
} else {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Opps!! Incorrect
Login Credentials"
);
echo
json_encode($server__response__error);
}
} catch (Exception $ex) {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Opps!! Something Went
Wrong! " . $ex->getMessage()
);
echo
json_encode($server__response__error);
}
} else {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Invalid API parameters!
Please contact the administrator or refer to the
documentation for assistance."
);
echo json_encode($server__response__error);
}
} else {
http_response_code(404);
$server__response__error = array(
"code" => http_response_code(404),
"status" => false,
"message" => "Bad Request"
);
echo json_encode($server__response__error);
}
OUTPUT
Thoroughly test your REST API using tools like Postman or cURL.
TEST CASE 1 – With Valid Input
Copy Code
{
"code": 200,
"status": true,
"message": "User Verified",
"userData": {
"fullName": "AppWeb Coders",
"emailID": "appwebcoders@gmail.com",
"userName": "appwebcoders"
}
}
TEST CASE 2 – With In-valid Input
Copy Code
{
"code": 404,
"status": false,
"message": "Opps!! Incorrect Login Credentials"
}
Enhancing Security
with Token-based
Authentication
To enhance security, we can implement token-based authentication. After a
successful login, we generate a unique token using JWT (JSON Web
Token) and return it to the client. This token should be attached to all
subsequent API requests for authentication. Although this tutorial does not
include the implementation of JWT, if you would like an article on that topic,
please leave a comment at the end of this article. We will consider your
feedback and may update or add a new article to cover JWT
implementation.
Conclusion
In conclusion, building a secure Login and Registration REST API in PHP
is an essential skill for modern web developers. By leveraging RESTful
principles, creating a structured development environment, and
implementing robust security measures, you can develop an
authentication mechanism that safeguards user data while offering a
seamless user experience.
This tutorial has provided a comprehensive guide to crafting a fully
functional Login and Registration REST API in PHP. By following the
steps outlined, you can create an authentication system that adheres to
best practices and serves as a foundation for secure web applications.
(Note: This article offers a comprehensive overview of
creating a Login and Registration REST API in PHP,
complete with code snippets. For in-depth
implementation details, refer to relevant online
resources and documentation.)
We would highly value your feedback and welcome any queries you
might have regarding this article. Please don’t hesitate to share your
thoughts, ask questions, or seek clarification. Your input will contribute
to enhancing the content and providing you with the most informative
experience. Thank you for taking the time to engage with us!

More Related Content

PPTX
Asymptotic Notations
PPTX
Introduction to Flowcharts
PPTX
Measuring algorithm performance
PPTX
Algorithm - Introduction
PPT
B-tree & R-tree
PPTX
Armstrong Number presentation
PPTX
Parsing LL(1), SLR, LR(1)
Asymptotic Notations
Introduction to Flowcharts
Measuring algorithm performance
Algorithm - Introduction
B-tree & R-tree
Armstrong Number presentation
Parsing LL(1), SLR, LR(1)

Similar to How to Create Login and Registration API in PHP.pdf (20)

PDF
Create a res tful services api in php.
PPT
Intro to php
PPTX
CHAPTER six DataBase Driven Websites.pptx
PPT
Php frameworks
PPTX
18.register login
PPT
P H P Part I I, By Kian
PPTX
This slide show will brief about database handling
PPSX
Php session
PPTX
User registration and login using stored procedure in php
PPT
Php Security By Mugdha And Anish
DOC
Creating a Simple PHP and MySQL-Based Login System
PDF
Php summary
PDF
The Zen of Lithium
DOCX
Apache Drill with Oracle, Hive and HBase
PDF
Workshop quality assurance for php projects - ZendCon 2013
PPTX
Sql server ___________session_18(stored procedures)
PPS
PHP Security
PPS
Php security3895
ODP
CodeIgniter PHP MVC Framework
ODP
Exploring Symfony's Code
Create a res tful services api in php.
Intro to php
CHAPTER six DataBase Driven Websites.pptx
Php frameworks
18.register login
P H P Part I I, By Kian
This slide show will brief about database handling
Php session
User registration and login using stored procedure in php
Php Security By Mugdha And Anish
Creating a Simple PHP and MySQL-Based Login System
Php summary
The Zen of Lithium
Apache Drill with Oracle, Hive and HBase
Workshop quality assurance for php projects - ZendCon 2013
Sql server ___________session_18(stored procedures)
PHP Security
Php security3895
CodeIgniter PHP MVC Framework
Exploring Symfony's Code
Ad

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
RMMM.pdf make it easy to upload and study
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Pharma ospi slides which help in ospi learning
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Classroom Observation Tools for Teachers
Supply Chain Operations Speaking Notes -ICLT Program
RMMM.pdf make it easy to upload and study
PPH.pptx obstetrics and gynecology in nursing
Pharmacology of Heart Failure /Pharmacotherapy of CHF
TR - Agricultural Crops Production NC III.pdf
VCE English Exam - Section C Student Revision Booklet
Abdominal Access Techniques with Prof. Dr. R K Mishra
Insiders guide to clinical Medicine.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pharma ospi slides which help in ospi learning
O7-L3 Supply Chain Operations - ICLT Program
Anesthesia in Laparoscopic Surgery in India
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Basic Mud Logging Guide for educational purpose
Week 4 Term 3 Study Techniques revisited.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Pre independence Education in Inndia.pdf
Classroom Observation Tools for Teachers
Ad

How to Create Login and Registration API in PHP.pdf

  • 1. How to Create Login and Registration API in PHP In today’s article, we will explore the concept of REST API and delve into creating a login and registration system using these APIs. In the contemporary landscape of web development, establishing strong and secure authentication systems is of utmost significance. A highly effective approach is to construct a Login and Registration system through the utilization of REST APIs. This article aims to provide you with a comprehensive walkthrough, enabling you to construct a robust and
  • 2. efficient user authentication system from the ground up, harnessing the capabilities of REST architecture. What is REST API REST (Representational State Transfer) APIs act as a bridge between the client and the server, facilitating effective communication between them. They utilize HTTP requests to transfer data and are an optimal choice for constructing systems due to their stateless nature. REST APIs provide a seamless integration experience across a variety of platforms and devices.
  • 3. PHP Login and Registration REST API Before we start coding, ensure you have a development environment set up. Install a web server (e.g., Apache), PHP, and a database (such as MySQL). Organize your project directory and create separate folders for PHP files, configurations, and assets. 1. Designing the Database Structure For REST APIs
  • 4. DATABASE NAME TABLE NAME APPWEBRESTAPI USERS CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `full_name` text NOT NULL, `phone_number` text NOT NULL, `email_id` text NOT NULL, `username` text NOT NULL, `password` text NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 5. 2. Creating Files and Folders For the Projects Note: In this tutorial, we are utilizing PDO for all database operations. If you are interested in learning about using MySQL or MySQLi, please leave a comment indicating your preference. I will either update this tutorial or create a new article on that topic as well. Creating files and folders for our projects is an essential step in organizing and managing our code.
  • 7. Configrations.php <?php // DEVELOPEMENT SERVER DETAILS ... $DATABASE_SERVER_IP = "localhost"; // put your database server host $DATABASE_USER_NAME = "root"; // put your database username $DATABASE_USER_PASSWORD=""; // put your database password, there is no default password $DATABASE_NAME="appwebrestapi"; // your database name
  • 8. DBConnect.php <?php require_once 'configurations.php'; try { $con = new PDO( "mysql:host=$DATABASE_SERVER_IP; dbname=$DATABASE_NAME", $DATABASE_USER_NAME, $DATABASE_USER_PASSWORD ); // set the PDO error mode to exception $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> DOWNLOAD CODE FROM GIT
  • 9. Implementing User Registration REST API: Before implementing registration, it’s essential to understand why we are using the POST method for the registration. Using the POST method for login and registration in our APIs with PHP, is crucial to ensure the security and integrity of sensitive user data. The POST method offers a secure way to transmit information by sending data in the HTTP request body, rather than exposing it in the URL. This protects sensitive information like passwords from accidental exposure through browser history, bookmarks, or shared links. With its ability to handle larger and more complex data payloads, the POST method supports the secure transfer of user credentials and additional registration details. By using POST, developers can implement essential security measures such as
  • 10. Cross-Site Request Forgery (CSRF) tokens, process data server-side, and adhere to best practices, contributing to a robust and secure authentication process. <?php header('Content-type: application/json'); if($_SERVER['REQUEST_METHOD']==='POST'){ $server__response__success = array( "code"=>http_response_code(200), "status"=>true, "message"=>"Request Accepted" ); echo json_encode($server__response__success); } else { http_response_code(404); $server__response__error = array( "code"=>http_response_code(404), "status"=>false, "message"=>"Bad Request" ); echo json_encode($server__response__error); }
  • 11. Before proceeding further, it is necessary to explain why I am using $_SERVER[‘REQUEST_METHOD’]. $_SERVER[‘REQUEST_METHOD’] is a built-in PHP superglobal variable that holds the HTTP request method used by the client to access the current script. It provides valuable information about how the request was made, whether it was through the GET, POST, PUT, DELETE, or other HTTP methods. Developers often use $_SERVER[‘REQUEST_METHOD’] to determine the nature of the request and handle different actions accordingly, such as processing form data, handling API endpoints, or performing specific server-side operations based on the HTTP method used. This versatile variable plays a fundamental role in routing and processing incoming requests in PHP applications.
  • 12. Here, we are only accepting POST requests. When any other request type is sent to the server, the API will reject the request and respond with a 404 error to the client. Example with GET request
  • 13. Example with POST request
  • 14. Proceed with the implementation now (Final Code). <?php header('Content-type: application/json'); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ( !empty($_POST['fullName']) && !empty($_POST['phoneNumber']) && !empty($_POST['emailID']) && !empty($_POST['userName']) && !empty($_POST['userPassword']) ) { $fullName = $_POST['fullName']; $phoneNumber = $_POST['phoneNumber']; $emailID = $_POST['emailID']; $userName = $_POST['userName']; $userPassword = $_POST['userPassword']; try { require 'DBConnect.php'; // check for duplicate user // here I am check for user email id for the same $SELECT__USER__SQL = "SELECT * FROM `users` WHERE users.email_id=:emailID;"; $duplicate__user__statement = $con->prepare($SELECT__USER__SQL); $duplicate__user__statement->bindParam(':emailID', $emailID, PDO::PARAM_STR); $duplicate__user__statement->execute();
  • 15. $duplicate__user__flag = $duplicate__user__statement->rowCount(); if ($duplicate__user__flag > 0) { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "This user is already registered." ); echo json_encode($server__response__error); } else { // insert/add new user details // encrypt user password $password__hash = password_hash($userPassword, PASSWORD_DEFAULT); $data__parameters = [ "fullName" => $_POST['fullName'], "phoneNumber" => $_POST['phoneNumber'], "emailID" => $_POST['emailID'], "userName" => $_POST['userName'], "userPassword" => $password__hash ]; // insert data into the database $SQL__INSERT__QUERY = "INSERT INTO `users`( `full_name`, `phone_number`, `email_id`,
  • 17. echo json_encode($server__response__success); } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Failed to create user. Please try again." ); echo json_encode($server__response__error); } } } catch (Exception $ex) { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Opps!! Something Went Wrong! " . $ex->getMessage() ); echo json_encode($server__response__error); } // end of try/catch } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Invalid API parameters! Please contact the administrator or refer to the documentation for assistance." );
  • 18. echo json_encode($server__response__error); } // end of Parameters IF Condition } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Bad Request" ); echo json_encode($server__response__error); } In the above code, we are also checking for duplicate user registration to prevent redundant records from being entered into the database.
  • 19. OUTPUT Thoroughly test your REST API using tools like Postman or cURL. TEST CASE 1 – With Valid Input { "code": 200, "status": true, "message": "User successfully created." } TEST CASE 2 – With In-valid Input
  • 20. Copy Code { "code": 404, "status": false, "message": "This user is already registered." } Implementation of User Login API Develop another PHP script, Login.php, to handle user login. Validate the provided login credentials against stored data in the database.
  • 21. <?php header('Content-type: application/json'); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!empty($_POST['userName']) && !empty($_POST['userPassword'])) { $userName = $_POST['userName']; $userPassword = $_POST['userPassword']; try { require 'DBConnect.php'; // checking for valid user details $SELECT__USER__DATA = "SELECT * FROM `users` WHERE users.username=:userName"; $select__user__statement = $con->prepare($SELECT__USER__DATA); $select__user__statement->bindParam(':userName', $userName, PDO::PARAM_STR); $select__user__statement->execute(); $user__flag = $select__user__statement->rowCount(); if ($user__flag > 0) { $user__data = $select__user__statement->fetch(PDO::FETCH_ASSOC); if (password_verify($userPassword, $user__data['password'])) { $user__object = array( "fullName"=>$user__data['full_name'],
  • 22. "emailID"=>$user__data['email_id'], "userName"=>$user__data['username'] ); http_response_code(200); $server__response__success = array( "code" => http_response_code(200), "status" => true, "message" => "User Verified" , "userData"=>$user__object ); echo json_encode($server__response__success); } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Opps!! Incorrect Login Credentials" ); echo json_encode($server__response__error); } } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Opps!! Incorrect Login Credentials"
  • 23. ); echo json_encode($server__response__error); } } catch (Exception $ex) { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Opps!! Something Went Wrong! " . $ex->getMessage() ); echo json_encode($server__response__error); } } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Invalid API parameters! Please contact the administrator or refer to the documentation for assistance." ); echo json_encode($server__response__error); } } else { http_response_code(404); $server__response__error = array( "code" => http_response_code(404), "status" => false, "message" => "Bad Request" ); echo json_encode($server__response__error); }
  • 24. OUTPUT Thoroughly test your REST API using tools like Postman or cURL. TEST CASE 1 – With Valid Input Copy Code
  • 25. { "code": 200, "status": true, "message": "User Verified", "userData": { "fullName": "AppWeb Coders", "emailID": "appwebcoders@gmail.com", "userName": "appwebcoders" } } TEST CASE 2 – With In-valid Input Copy Code { "code": 404, "status": false, "message": "Opps!! Incorrect Login Credentials" }
  • 26. Enhancing Security with Token-based Authentication To enhance security, we can implement token-based authentication. After a successful login, we generate a unique token using JWT (JSON Web Token) and return it to the client. This token should be attached to all subsequent API requests for authentication. Although this tutorial does not include the implementation of JWT, if you would like an article on that topic, please leave a comment at the end of this article. We will consider your feedback and may update or add a new article to cover JWT implementation.
  • 27. Conclusion In conclusion, building a secure Login and Registration REST API in PHP is an essential skill for modern web developers. By leveraging RESTful principles, creating a structured development environment, and implementing robust security measures, you can develop an authentication mechanism that safeguards user data while offering a seamless user experience. This tutorial has provided a comprehensive guide to crafting a fully functional Login and Registration REST API in PHP. By following the steps outlined, you can create an authentication system that adheres to best practices and serves as a foundation for secure web applications.
  • 28. (Note: This article offers a comprehensive overview of creating a Login and Registration REST API in PHP, complete with code snippets. For in-depth implementation details, refer to relevant online resources and documentation.) We would highly value your feedback and welcome any queries you might have regarding this article. Please don’t hesitate to share your thoughts, ask questions, or seek clarification. Your input will contribute to enhancing the content and providing you with the most informative experience. Thank you for taking the time to engage with us!