Skip to content
No results
  • Home
  • Blog
  • Tutorials
    • Mysql
    • PHP
    • PHP OOP
    • API
    • Jquery
    • Ajax
    • Javascript
    • JSON
    • Bootstrap
    • WordPress
  • Framework
    • Laravel 9
    • CakePHP 4
    • Codeingniter
  • Payment Gateway
  • Tools
    • Try Online Editor
  • Live Demo

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.

  • Home
  • About us
  • Privacy Policy
  • Terms & Conditions
  • Contact us
  • Disclaimer
  • Sitemap
Facebook Twitter Instagram LinkedIn Medium Pinterest
Webs Codex
  • Home
  • Blog
  • Tutorials
    • Mysql
    • PHP
    • PHP OOP
    • API
    • Jquery
    • Ajax
    • Javascript
    • JSON
    • Bootstrap
    • WordPress
  • Framework
    • Laravel 9
    • CakePHP 4
    • Codeingniter
  • Payment Gateway
  • Tools
    • Try Online Editor
  • Live Demo
Webs Codex
Home Ajax Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

  • ManishManish
  • January 7, 2021
  • Ajax, Jquery, Mysql, PHP
  • 5
Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

Normally after a user is registered, we will send an email to the user\’s registration email address to verify their email address. Once the user clicks the link for the confirmation email, the user registration process will be completed with an email confirmation.

However, in this post, we are using the OTP (One Time Password) method to verify the registered user’s email address. Email verification is an indispensable process to verify that registered users entered correct information when registering.

This is also useful for preventing spam from being registered in our web application. For this reason, we verify the identity of the user and must confirm their email address. With this OTP method, if the user has provided us with a real email address, our system will send an email to that email address to confirm the email with the OTP number.

All the user has to do is copy this OTP number and enter the email confirmation page that is loaded after submitting the registration form data. On this webpage the user must enter the OTP number and submit the form. After submitting the form, the user’s email address is verified.

Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

Table of Contents

  • Create Database and Table
  • Create Database Connection with Mysql
  • User Registration HTML Form with jQuery AJAX
  • User Registration PHP code
  • User Login HTML Form with jQuery AJAX
  • Login Page Output
  • Sending mails using your Google account from your local/online server using PHPMailer
  • After Send OTP 
  • Create Send OTP to Email
  • OTP to Email Output
  • Create Verify OTP File
  • Create Dashboard file after successful login.
  • Create Logout File

Create Database and Table

In the first step we need to create a database and tables. That’s why I created a database here with “webscodex” and “users” tables with identifier and email fields. Just create the users table as described in the SQL query.

--
-- Database: `webscodex`

-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `mobile_number` varchar(50) NOT NULL,
  `otp` varchar(50) NOT NULL,
  `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Create Database Connection with Mysql

config.php

<?php

	// Database configuration 	
	$hostname = "localhost"; 
	$username = "root"; 
	$password = ""; 
	$dbname   = "webscodex";
	 
	// Create database connection 
	$con = new mysqli($hostname, $username, $password, $dbname); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	}

?>

User Registration HTML Form with jQuery AJAX

I have created three HTML view login form, registration form and the dashboard for this code. submit form using jQuery AJAX to register using without refresh page.

See also  Filter or Search with Date Range using jQuery AJAX Date Picker with PHP MySQL

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>

<div class="card text-center" style="padding:20px;">
  <h3>Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql</h3>
</div><br>

<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
      <div class="col-md-6">        
        <form id="submitForm">
          <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name" placeholder="Enter Name" required="">
          </div>
          <div class="form-group">  
            <label for="mobile">Mobile Number:</label>
            <input type="text" class="form-control" name="mobile" placeholder="Enter Mobile number" required="">
          </div>
          <div class="form-group">  
            <label for="nmail">Email:</label>
            <input type="text" class="form-control" name="email" placeholder="Enter Email" required="">
          </div>
          <div class="form-group">
            <p>Already have account ?<a href="login.php"> Login</a></p>
            <button type="submit" class="btn btn-primary">Sign Up</button>
          </div>
        </form>
      </div>
  </div>
</div>

<script type="text/javascript">
  $(document).ready(function(){
    $("#submitForm").on("submit", function(e){
      e.preventDefault();
      var formData = $(this).serialize();
      $.ajax({
        url  : "signup.php",
        type : "POST",
        cache:false,
        data : formData,
        success:function(result){
          if (result == "yes") {
            alert("Registration sucessfully Please login");
            window.location ='login.php';          
          }else{
            alert("Registration failed try again!");
          }          
        }
      });  
    });    
  });
</script>
</body>
</html>

User Registration PHP code

After jQuery AJAX form is submitted than send to the url signup.php for the PHP code.

signup.php

<?php

  // Include database connection file

  include_once('config.php');

  if (isset($_POST['email'])) {
    
    $name   = $con->real_escape_string($_POST['name']);
    $mobile = $con->real_escape_string($_POST['mobile']);
    $email  = $con->real_escape_string($_POST['email']);
    $otp    = mt_rand(1111, 9999);

    $query  = "INSERT INTO users (name,email,mobile_number,otp) VALUES ('$name','$email','$mobile','$otp')";

    $result = $con->query($query);

    if ($result) {
        echo "yes";
    }else{
        echo "no";
    }   

  }
?>

User Login HTML Form with jQuery AJAX

login.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>

<div class="card text-center" style="padding:20px;">
  <h3>Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql</h3>
</div><br>

<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
      <div class="col-md-6">   

        <div class="alert alert-success alert-dismissible" style="display: none;">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <span class="success-message"></span>
        </div>

        <form id="emailForm">
          <div class="form-group">  
            <label for="email">Email:</label> 
            <input type="text" class="form-control" name="email" placeholder="Enter Email" required="" id="email">
            <span class="error-message" style="color:red;"></span>
          </div>
          <div class="form-group">
            <p>Not registered yet ?<a href="index.php"> Register here</a></p>
            <button type="submit" class="btn btn-primary" id="sendOtp">Send OTP</button>
          </div>
        </form>

        <form id="otpForm" style="display:none;">
          <div class="form-group">  
            <label for="mobile">OTP:</label>
            <input type="text" class="form-control" name="otp" placeholder="Enter OTP" required="" id="otp">
            <span class="otp-message" style="color: red;"></span>
          </div>
          <div class="form-group">
            <button type="submit" class="btn btn-success" id="verifyOtp">Verify OTP</button>
          </div>
        </form>        
      </div>
  </div>
</div>

<script type="text/javascript">
  $(document).ready(function(){

    // Send OTP email jquery
    $("#sendOtp").on("click", function(e){ 
      e.preventDefault();    
      var email = $("#email").val();
      $.ajax({
        url  : "send_otp.php",
        type : "POST",
        cache:false,
        data : {email:email},
        success:function(result){
          if (result == "yes") {
            $("#otpForm,.alert-success").show();
            $("#emailForm").hide();
            $(".success-message").html("OTP sent your email address");
          }
          if (result =="no") {
            $(".error-message").html("Please enter valid email");
          }        
        }
      });  
    });   

    // Verify OTP email jquery
    $("#verifyOtp").on("click",function(e){
      e.preventDefault();
      var otp = $("#otp").val();
      $.ajax({
        url  : "verify_otp.php",
        type : "POST",
        cache:false,
        data : {otp:otp},
        success:function(response){
          if (response == "yes") {
            window.location.href='dashboard.php';
          }
          if (response =="no") {
            $(".otp-message").html("Please enter valid OTP");
          }        
        }
      });
    });
  });
</script>
</body>
</html>

Login Page Output

Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

Sending mails using your Google account from your local/online server using PHPMailer

You can use the PHP mail function to send emails to users. However, most of the time this won’t work on your local server. There is an excellent plugin that I use in most of my PHPMAILER projects. You can send good looking HTML emails using Gmail or any other email account using SMTP. All you have to do is set your email address, password, host name and port name. If you want to learn how to Send Email from localhost in PHP.

See also  Live Search in PHP Mysqli using jQuery AJAX

After Send OTP 

Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

Create Send OTP to Email

send_otp.php

<?php

  // Start session   
  session_start();

  // Include database connection file

  include_once('config.php');

  // Send OTP to email Form post
  if (isset($_POST['email'])) {
      
      $email  = $con->real_escape_string($_POST['email']);
      $otp    = mt_rand(1111, 9999);
      $query  = "SELECT * FROM users WHERE email = '$email'";
      $result = $con->query($query);

      if ($result->num_rows > 0) {
          $con->query("UPDATE users SET otp = '$otp' WHERE email = '$email'");
          sendMail($email, $otp);
          $_SESSION['EMAIL'] = $email; 
          echo "yes";
      }else{
          echo "no";
      }            
  }


  // Create function for send email

  function sendMail($to, $msg){

    require 'PHPMailer/PHPMailerAutoload.php';

    $mail = new PHPMailer;
    
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output

    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'YourEmailAddress';                 // SMTP username
    $mail->Password = 'YourEmailPassword';                // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->setFrom('FromEmail', 'OTP Verification');
    $mail->addAddress($to, 'OTP Verification');           // Add a recipient
   
    $mail->isHTML(true);                                  // Set email format to HTML

    $mail->SMTPOptions = array(
        'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
      )
    );

    $mail->Subject = 'OTP Verification';
    $mail->Body    = 'Your verification OTP Code is <b>'.$msg.'</b>';
    
    if($mail->send()) {
        return true;
    } else {
        return false;
    }
    
  }

?>

OTP to Email Output

Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

Create Verify OTP File

verify_otp.php

<?php

  // Start session   
  session_start();

  // Include database connection file

  include_once('config.php');

  // Send OTP to email Form post
  if (isset($_POST['otp'])) {
     	
        $postOtp = $_POST['otp'];
        $email  = $_SESSION['EMAIL'];
        $query  = "SELECT * FROM users WHERE otp = '$postOtp' AND email = '$email'";
        
        $result = $con->query($query);
        if ($result->num_rows > 0) {
            $con->query("UPDATE users SET otp = '' WHERE email = '$email'");
            $_SESSION['IS_LOGIN'] = $email; 
            echo "yes";         
        }else{
            echo "no";
        }          
    }
?>

Create Dashboard file after successful login.

dashboard.php

<?php
session_start();
if (isset($_SESSION['IS_LOGIN'])) {
    echo "Hello" . "  ". "<b>" . ucwords($_SESSION['EMAIL']). "</b>";		
}else{
    header("Location:login.php");
    die();
}
?>
<br><br>
<p><a href="logout.php">Logout</a></p>

Create Logout File

logout.php

<?php
    session_start();
    session_destroy();
    unset($_SESSION['EMAIL']);
    unset($_SESSION['IS_LOGIN']);
    header("Location:login.php");
?>
You can always support by sharing on social media or recommending my blog to your friends and colleagues.   
If you have any suggestions / problems about this tutorial, please comment on the  form below.😊
# AJAX# EMAIL# jQuery# LOGIN# MYSQL# otp# PHP
Previous Post Drag and Drop upload file using Dropzone JS with PHP & Mysqli
Next Post Implement captcha code login validation in PHP with Mysql

Related Blog Posts

How to Send Bulk Emails in PHP using PHPMailer with Ajax jQuery

How to Created PHP CRUD using OOPS with MYSQLi in MVC

Generate PDF File From MySQL Database Using PHP

5 Comments

Leave a ReplyCancel Reply

Your email address will not be published. Required fields are marked *

  1. Manish

    sonu

    March 17, 2021 / 3:49 pm Reply

    hiiiiiiiiiiii

  2. Manish

    sonu

    March 17, 2021 / 3:49 pm Reply

    ok……………………………….

  3. Manish

    Webs Codex

    March 17, 2021 / 3:49 pm Reply

    Hi

  4. Manish

    Webs Codex

    August 18, 2021 / 9:04 pm Reply

    Yes

  5. Manish

    CodingBot

    August 18, 2021 / 9:03 pm Reply

    can we run in xampp localhost

Recent Posts

  • Razorpay Payment Gateway Integration in PHP
  • Paytm Payment Gateway Integration in PHP Step by Step
  • How to Export excel data from Database in PHP using Spreadsheet
  • Import Excel File into MySQL Database in PHP using Spreadsheet
  • What is an API? What is an API integration ?

Follow on Facebook

Tutorial Categories

  • Ajax (38)
  • API (1)
  • CakePHP 4 (6)
  • How To (15)
  • Javascript (1)
  • Jquery (42)
  • JSON (2)
  • Mysql (44)
  • Payment Gateway (2)
  • PHP (56)
  • PHP OOP (7)

Follow on Social

Facebook Twitter Instagram LinkedIn Pinterest Medium

Trending now

How to Send Bulk Emails in PHP using PHPMailer with Ajax jQuery
How to Created PHP CRUD using OOPS with MYSQLi in MVC
Generate PDF File From MySQL Database Using PHP
Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql

About Webs codex

Webs Codex is a free online resource on programming and web development for beginners to advance. It was founded in Jan 2020 by Manish Pushpakar to deliver the best and fresh articles for students and our readers to skill up as they would like to. we are share multiple technologies tutorials.

Customer Area

  • About us
  • Disclaimer
  • Contact us
  • Privacy Policy
  • Terms & Conditions
  • About us
  • Disclaimer
  • Contact us
  • Privacy Policy
  • Terms & Conditions

Quick Links

  • How To
  • Live Demo
  • Github Code
  • Interview Questions
  • Try Online Editor
  • How To
  • Live Demo
  • Github Code
  • Interview Questions
  • Try Online Editor

Copyright © 2020-22 Webscodex.com All rights reserved