SlideShare a Scribd company logo
1 of 28
Download to read offline
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.
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

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

Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemAzharul Haque Shohan
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Apache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBaseApache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBaseNag Arvind Gudiseva
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)Ehtisham Ali
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHPYogesh singh
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 

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

Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 
Php summary
Php summaryPhp summary
Php summary
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Apache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBaseApache Drill with Oracle, Hive and HBase
Apache Drill with Oracle, Hive and HBase
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)
 
Php security3895
Php security3895Php security3895
Php security3895
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Framework
FrameworkFramework
Framework
 
REST API for your WP7 App
REST API for your WP7 AppREST API for your WP7 App
REST API for your WP7 App
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHP
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 

Recently uploaded

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 

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.
  • 6.
  • 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!