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;
Watch Video for Demo
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();
}
?>
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
{
"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
{
"code": 200,
"status": true,
"message": "User Verified",
"userData": {
"fullName": "AppWeb Coders",
"emailID": "appwebcoders@gmail.com",
"userName": "appwebcoders"
}
}
TEST CASE 2 – With In-valid Input
{
"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!
It be will a really very helpful for implementing
the REST API concept.
@thanks appwebcoders for this amazing step by step clarifications.
Thank You for your feedback. @Danish you can explore more articles to enhance your coding
Great tutorial! Your step-by-step guide on creating a Login and Registration API in PHP was incredibly helpful. I appreciate how you not only explained the code but also provided insightful explanations for each component, making it easy for beginners like me to understand the process. Again Thank You Appweb Coders
Thank You for your feedback. @Inesh you can explore more articles to enhance your coding
Thank you for your dedication to helping learners like me. Your article has made a significant impact on my learning journey, and I’m excited to continue exploring PHP with the newfound understanding your article has provided.
Thank You for your feedback. @Szamal you can explore more articles to enhance your coding
[…] To implement an AJAX request for the login page, we need to understand the REST API. If you’re not familiar with the REST API, you’ll need to read this article. How to Create Login and Registration API in PHP […]
This article is really amazing, thank you for sharing helpful article. very interesting and amazing details you provide. Wonderful & very informative article