In this tutorial, You will learn to create the Login and Registration rest API using PHP & MySQL which will be very useful to integrate with frontend languages such as react js, angular js & more.
Step to Create Login and Registration Api in PHP & MYSQL
Now, Let’s start coding with the given some simple steps –
Create a Folder Structure
First of all, Create the following folder structure in your system.
- database.php – This file is created for the database connection
- api.php – This file is created for the API requests such as post, put, get & delete.
- CrudApi.php – This file is created for writing code with a custom class for crud operation
registration-login/ |_rest/ | |__database.php | |__login-api.php |__Login.php |__registration-api.php |__Registration.php
Create Database & Table
Now, Create a database & Table in the PhpMyAdmin the the following given name –
Database Name – restapi
CREATE DATABASE restapi
Table Name – developers
CREATE TABLE `users` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `firstName` varchar(255) DEFAULT NULL, `lastName` varchar(255) DEFAULT NULL, `gender` varchar(10) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, )
Connect to Database
No, Connect your PHP to the MySQL database with this code.
File Name – database.php
<?php $host = "localhost"; $user = "root"; $password = ""; $database = "phprestapi"; $conn = new mysqli($host, $user, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
Create Registration Api Script
File Name – Registration.php
<?php class Registration { private $conn; private $categoryTable; public function __construct($conn) { $this->conn = $conn; $this->tableName = 'users'; } public function validate($firstName, $lastName, $gender, $email, $password) { $error = false; $errMsg = null; if(empty($firstName)) { $errMsg = "First Name is empty"; $error = true; } if(empty($lastName)) { $errMsg = "Last Name is empty"; $error = true; } if(empty($gender)) { $errMsg = "Gender is empty"; $error = true; } if(empty($email)) { $errMsg = "Email is empty"; $error = true; } if(empty($password)) { $errMsg = "Password is empty"; $error = true; } $errorInfo = [ "error" => $error, "errMsg" => $errMsg ]; return $errorInfo; } public function create() { $data = json_decode(file_get_contents("php://input"), true); $firstName = $data['firstName']; $lastName = $data['lastName']; $gender = $data['gender']; $email = $data['email']; $password = $data['password']; $check = $this->getByEmail($email); if(!$check) { $validate = $this->validate($firstName, $lastName, $gender, $email, $password); $success = false; if (!$validate['error']){ $query = "INSERT INTO "; $query .= $this->tableName; $query .= " (firstName, lastName, gender, email, password ) "; $query .= " VALUES (?, ?, ?, ?, ?)"; $stmt = $this->conn->prepare($query); $stmt->bind_param("sssss", $firstName, $lastName, $gender, $email, $password); if ($stmt->execute()) { $status = 200; $msg = "You are registered successfully"; } else{ $status = 400; $msg = $this->conn->error; } } else { $status = 401; $msg = $validate['errMsg']; } } else{ $status = 401; $msg = "This email already registered"; } $data = [ 'status' => $status, 'msg' => $msg, 'data' => $data ]; return json_encode($data); } public function getByEmail($email) { $isExist = false; $query = "SELECT email FROM "; $query .= $this->tableName; $query .= " WHERE email=?"; $stmt = $this->conn->prepare($query); $stmt->bind_param("s", $email); if ($stmt->execute()) { $result = $stmt->get_result(); $rows= $result->fetch_assoc(); if ($result->num_rows > 0) { $isExist = true; } } return $isExist; } } ?>
Create Registration API Action
File Name – registration-api.php
<?php require_once 'database.php'; require_once 'Registration.php'; $registeration = new Registration($conn); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type"); header("Content-Type: application/json"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); } // HTTP method handling $method = $_SERVER['REQUEST_METHOD']; switch ($method) { case 'POST': echo $registeration->create(); break; default: header('HTTP/1.0 405 Method Not Allowed'); break; } ?>
Create Login Api Script
File Name – Login.php
<?php class Login { private $conn; private $categoryTable; public function __construct($conn) { $this->conn = $conn; $this->tableName = 'users'; } public function validate($email, $password) { $error = false; $errMsg = null; if(empty($email)) { $errMsg = "Email is empty"; $error = true; } if(empty($password)) { $errMsg = "Password is empty"; $error = true; } $errorInfo = [ "error" => $error, "errMsg" => $errMsg ]; return $errorInfo; } public function getLogin() { $data = json_decode(file_get_contents("php://input"), true); $email = $data['email']; $password = $data['password']; $validate = $this->validate($email, $password); if (!$validate['error']){ $query = "SELECT id, firstName, lastName, gender FROM "; $query .= $this->tableName; $query .= " WHERE email=? AND password=?"; $stmt = $this->conn->prepare($query); $stmt->bind_param("ss", $email, $password); if ($stmt->execute()) { $result = $stmt->get_result(); $rows= $result->fetch_assoc(); if ($result->num_rows > 0) { $token = md5(uniqid()); $query = "UPDATE "; $query .= $this->tableName; $query .= " SET token =? "; $query .= " WHERE id = ?"; $stmt = $this->conn->prepare($query); $stmt->bind_param("ss", $token, $rows['id']); $stmt->execute(); $status = 200; $msg = "Logged in successfully"; $data = $rows; $data = [ 'status' => 200, 'msg' => "Logged in successfully", 'data' => $rows ]; } else { $data = [ 'status' => 404, 'msg' => "Invalid User", 'data' => [] ]; } } } else { $data = [ 'status' => 401, 'msg' => $validate['errMsg'], 'data' => [] ]; } return json_encode($data); } } ?>
Create Login Api Action
File Name – login-api.php
<?php require_once 'database.php'; require_once 'login.php'; $login = new Login($conn); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type"); header("Content-Type: application/json"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); } // HTTP method handling $method = $_SERVER['REQUEST_METHOD']; switch ($method) { case 'POST': echo $login->getLogin(); break; default: header('HTTP/1.0 405 Method Not Allowed'); break; } ?>
Run CRUD API With Postman
Now, open your Postman, and run the following API request
For Registration-
method – POST
URL
http://localhost/registration-login/rest/crud-operations/api.php
Payload – JSON data
{ "firstName": "Jhon", "lastName": "Doe", "gender": "male", "email": "example@gmail.com", "password": "uub87c@h#!ju12" }
For Login
method – POST
URL –
http://localhost/registration-login/rest/login-api.php
Payload – JSON Data
{ "email": "example@gmail.com", "password": "abd@g4!g#12" }