AdSense


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.


User Registration with Email Verification using PHP and Mysql,  Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql ,


Most dynamic websites have a user registration form. By filling out the user registration form, users can register on the website. Using the OTP code to verify a user's email address on this registration form is the safest method of verifying a user's email address. With this method, an OTP code is generated after the user submits the data for the registration form, and this OTP code is sent to the registered user's email address. When the user enters the OTP code, the PHP web application checks the user's email address against this OTP code.

In this tutorial, we will study the user registration process by checking email via the OTP method. Here we send the OTP code via email. When using this OTP code method, the user's email address is verified after the user enters the OTP number received in their email address. Below is the source code of the PHP registration system with the email verification process using the OTP method. The source code tells you how to create a registration form after we have checked the data for a user registration form with PHP functions.

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

Here you only need to take a few steps to proceed.

  1. Create Database and Table
  2. Create Database Connection with Mysql
  3. User Registration HTML Form with Jquery AJAX
  4. User Login HTML Form with Jquery AJAX
  5. Create Send OTP to Email.
  6. Create Verify OTP file.
  7. Create Dashboard file after successful login.
  8. Create Logout file

See also 


Step 1. 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.

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;


Step 2 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); 
	}

?>


Step 3 .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.

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";
    }   

  }
  
  

?>

Step 4 .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


User Registration with Email Verification using PHP and Mysql,  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.


After Send OTP 


User Registration with Email Verification using PHP and Mysql,  Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql ,


Step 5. Create Send OTP to Email and 

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

User Registration with Email Verification using PHP and Mysql,  Registration & Login with Email OTP verification using Jquery AJAX with PHP Mysql ,

Step 6.  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";
       } 
                 
  }

?>


Step 7. 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>


Step 8. 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.😊


Post a Comment

Previous Post Next Post