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

An OTP, or one-time password, is a fast and effective way to verify a user’s mobile number. Generally, OTP is sent to the user’s mobile number via SMS. Users need to submit a verification code to verify their mobile number. In this tutorial we will show you how to implement the OTP (One-Time Password Verification) process via SMS via PHP.

SMS Gateway provides an easy way to send text messages from a script to a mobile number. The SMS gateway API allows you to easily send an OTP code to the user\’s mobile number for verification. Most SMS gateway providers allow SMS to be sent via PHP scripts. In the sample code, we use the SMS gateway API to send SMS OTP using PHP.

In the previous tutorial we saw how to check email and login with OTP authentication via PHP. To verify a mobile number by sending an SMS OTP using the Textlocal API, you need to create a Textlocal account and log in with it to get an API key. This API key will be used later when creating an instance of the Curl API to send SMS

Preview:

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

Create Database and Table by SQL query

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); 
	}
?>

Create User Registration HTML Form with jQuery AJAX

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Registration & Login with mobile 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 mobile 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="email">Email:</label>
            <input type="email" 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>

Create User Registration PHP File

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

Create User Login HTML Form with jQuery AJAX

login.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Registration & Login with Mobile 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 Mobile 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">×</a>
          <span class="success-message"></span>
        </div>

        <form id="mobileForm">
          <div class="form-group">  
            <label for="mobile">Mobile:</label> 
            <input type="text" class="form-control" name="mobile" placeholder="Enter Mobile" required="" 
            id="mobile">
            <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 mobile jquery
    $("#sendOtp").on("click", function(e){ 
      e.preventDefault();    
      var mobile = $("#mobile").val();
      $.ajax({
        url  : "send_otp.php",
        type : "POST",
        cache:false,
        data : {mobile:mobile},
        success:function(result){
          if (result == "yes") {
            $("#otpForm,.alert-success").show();
            $("#mobileForm").hide();
            $(".success-message").html("OTP sent your mobile number");
          }
          if (result =="no") {
            $(".error-message").html("Please enter valid mobile number");
          }        
        }
      });  
    });   

    // Verify OTP mobile 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>

Preview

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

Create User Login Send OTP with SMS gateway API to mobile PHP File

send_otp.php

<?php

  // Start session   
  session_start();

  // Include database connection file

  include_once('config.php');

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

      if ($result->num_rows > 0) {
         $con->query("UPDATE users SET otp = '$otp' WHERE mobile_number = '$mobile'");
         // Check mobile number is not empty than send OTP
         if (!empty($mobile)) {
            sendSMS($mobile, $otp);
            $_SESSION['MOBILE'] = $mobile;
         }
         echo "yes";
      }else{
         echo "no";
      }            
   }


   // Create a common function for send SMS
   function sendSMS($mobile, $otp) {
      // Account details
      $apiKey = urlencode('Your API key');
      // Message details
      $numbers = array($mobile);
      $sender  = urlencode('TXTLCL');
      $message = rawurlencode('Your One Time Password is '.$otp.' for verification your account.');
      $numbers = implode(',', $numbers);
    
      // Prepare data for POST request
      $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);

      // Send the POST request with cURL
      $ch = curl_init('https://api.textlocal.in/send/');
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $response = curl_exec($ch);
      curl_close($ch);      
      // Process your response here
      return $response;
   }
?>

Create OTP verify Code in PHP 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'])) {
   	$otp    = $_POST['otp'];
   	$mobile = $_SESSION['MOBILE'];
 	  $query  = "SELECT * FROM users WHERE otp = '$otp' AND mobile_number = '$mobile'";
   	$result = $con->query($query);
        $row    = $result->fetch_array();
    
   if ($result->num_rows > 0) {
       	$con->query("UPDATE users SET otp = '' WHERE mobile_number = '$mobile'");
        $_SESSION['NAME'] = $row['name'];
       	echo "yes";         
   }else{
       	echo "no";
    }     
 }
?>

Preview:

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

Create dashboard or Profile File after verify OTP 

dashboard.php

<?php

session_start();

if (isset($_SESSION['MOBILE'])) {
    echo "Hello" . "  ". "<b>" . ucwords($_SESSION['NAME']). "</b>";		
}else{
    header("Location:login.php");
    die();
}

?>
<br><br>
<p><a href="logout.php">Logout</a></p>

Create Logout file in PHP

logout.php

<?php
   session_start();
   session_destroy();
   unset($_SESSION['MOBILE']);
   unset($_SESSION['NAME']);
   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 or problems about this tutorial, please comment on the  form below.😊

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

Leave a Reply

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