In this tutorial, we will learn how to Signup using Modal with OTP on mobile using PHP and MSG91 Library. These days OTP is considered as one of the important Authentication factors for the payment gateways, e-commerce websites/Apps Like Flipkart, Amazon etc. OTP basically use to authenticate the users. In this tutorial, we will use MSG91 Library.

Let’s get started, Create a project in your server folder(www). Name it “Signup_using_otp” I am using visual studio code which is one of my favorite code editors. First of all, create a database inside phpmyadmin name it “loginotp”. create a table inside the database and name it “Users”. Now create some columns same as shown in below image.

Source code: Download Now

Step-1:- Database Setup

In this step, we will create a PHP file and name it Database.php file. In this file create a class “Database“. we have created five function inside this class. __construct is PHP a special function which is called at the time of object creation. In __construct function make the database connection, so every time we create the object of Database class, database connection will automatically be created. There is a __destruct function which is also a special function of PHP. This function is called at the end of the script so we are going to close the database connection here. query function will execute the MySQL query as shown in the below code. getData function is used to get the data from the table. getlastid function will return the Maximum id from the table.

Database.php
<?php
    
class Database{

    public function __construct()
    {
        $hostname= "localhost";
        $username= "root";
        $password="mysql";
        $database="loginotp";

         $this->connection = 
                  mysqli_connect($hostname,$username,$password,$database);
    }

    // This will be called at the end of the script.
    public function __destruct()
    {
        mysqli_close($this->connection);
    }

    public function query($query)
    {
     return mysqli_query($this->connection,$query);      
    }

    public function getData($user_id){

       $sql = "SELECT * FROM users WHERE id = '$user_id' ";
       $query= mysqli_query($this->connection,$sql);  
       $row = mysqli_fetch_assoc($query);
       return $row;
    }

    public function getlastid(){

       $sql = "SELECT MAX(id) FROM users";
       $query= mysqli_query($this->connection,$sql);
       $row = $query->fetch_assoc();
       return $row['id'];
    }
}

?>

Related: Login Registration form using PHP and MySQL

Step-2:- Setup sending OTP

In this step, we will setup MSG91 API for sending OTP. Create a PHP file inside the project folder and name it “otpmessage.php“. Now create a class Otpmessage and create two functions sendotp and generateOtp . generateOtp function is used to generate a random number which will be sent to the user in the form of OTP. MSG91 API is used in sendotp function to send otp to the user. make sure if are changing the text message it should contain OTP else API will not send a message to the user. Create your own MSG91 API key as they offer 1000 free transactional message to developers.

otpmessage.php
<?php

class Otpmessage{

    public function generateOtp() {
        return rand(1000, 9000);
    }
    public function sendotp($mobile_number){
 
    $api_key="269387Avjxaztiygc5c9a40f8";    
    $senderId="MYTREN";     
	$otp = $this->generateOtp();
	$contactNumber= '91'.$mobile_number.'';
    $msg = 'your OTP is '.$otp.'. Donot share it with anyone';;

    $curl = curl_init();    

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://control.msg91.com/api/sendotp.php?otp_length=4&authkey=$api_key&message=$msg&sender=$senderId&mobile=$contactNumber&otp=$otp&otp_expiry=10",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "",
  CURLOPT_SSL_VERIFYHOST => 0,
  CURLOPT_SSL_VERIFYPEER => 0,
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

return $response;

   }

}

Related: Login Registration form using PHP and MySQL

Step:-3 Creating autoloader

In this step, we will create autoloader.php file. this file is not necessary but we have to create this file to load many PHP files by using a single PHP file. The motive of creating this file is to load all PHP file at once.

<?php

$database_class_name = "Database";

function __autoload($database_class_name) {
    require_once $database_class_name.'.php';
    require_once 'otpmessage.php';
}

Step-4:- Create Signup

Create another PHP file inside project folder name it signup.php In this file we are getting user information(name, email, phone, password) using POST method from ajax call and inserting information to table users. In the same file, we are sending an OTP to the user phone number.

<?php
 require_once 'autoloader.php';

$email= $_POST['email'];

$phone= $_POST['phone'];

//$password= $_POST['password'];
$password = md5($_POST['password']);
$name=$_POST['name'];;
$database = new Database();
$otpmessage = new otpmessage();

$verify="";

$user_created = $database->query("INSERT INTO users (name,phone,email,password)
VALUES ('$name', '$phone', '$email', '$password')");

if ($user_created) {    
    $otpmessage->sendotp($phone);
    $lastid=$database->getlastid();
        session_start();
        $_SESSION["user_id"] =$lastid;
    $verify="success";
}else {

    $verify="error";
    
}
echo $verify;

?>

Related: Learn more about Mysql Database

Step-5:- Verifying OTP

Now create another PHP file name it verifyotp.php which will verify the OTP. if OTP is verified successfully update the user’s table and set column verified to 1. which is used to authenticate the user.

<?php
require_once('database.php');
$contactNumber=$_POST['phone'];
$otp=$_POST['otp'];

$verify="";
$api_key="269387Avjxaztiygc5c9a40f8";
$mobile_number= '91'.$contactNumber.'';
     $curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://control.msg91.com/api/verifyRequestOTP.php?authkey=$api_key&mobile=$mobile_number&otp=$otp",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "",
  CURLOPT_SSL_VERIFYHOST => 0,
  CURLOPT_SSL_VERIFYPEER => 0,
  CURLOPT_HTTPHEADER => array(
    "content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

$json = json_decode($response, true);

if($json['type']=='success'){

     $database = new Database();
     
     $updatequery=$database->query("UPDATE users SET verified=1 WHERE phone = '$contactNumber' ");
     if ($updatequery) {
        $verify="success";
     } else{

        $verify= "error";
     }
    
    

}else {
    $verify="error";
}

echo $verify;
?>

Step-:- Modal Signup Page

Following PHP file will hold the front end. We have implemented a button called signup which opens the signup modal as shown in the image below.

There are four input fields i.e name, email, phone, password. once the details filled user click on register button. if the phone number is correct user gets the OTP and modal form change to verify OTP form as shown below image.

Index.php
<?php
 require_once 'autoloader.php';
session_start();
if(isset($_SESSION["user_id"])){

    $user_id = $_SESSION["user_id"];
    $database = new Database();
    $user_data = $database->getData($user_id);
    $user_name= $user_data['name'];
    $user_email= $user_data['email'];
    $user_phone= $user_data['phone'];
    
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Login Signup using Modal with OTP on mobile using PHP and MSG91 Library </title>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>


<style>

	.modal-login {
		width: 320px;
	}
	.modal-login .modal-content {
		border-radius: 1px;
		border: none;
	}
	.modal-login .modal-header {
        position: relative;
		justify-content: center;
        background: #f2f2f2;
	}
    .modal-login .modal-body {
        padding: 30px;
    }
    .modal-login .modal-footer {
        background: #f2f2f2;
    }
	.modal-login h4 {
		text-align: center;
		font-size: 26px;
	}
    .modal-login label {
        font-weight: normal;
        font-size: 13px;
    }
	.modal-login .form-control, .modal-login .btn {
		min-height: 38px;
		border-radius: 2px; 
	}
	.modal-login .hint-text {
		text-align: center;
	}
	.modal-login .close {
        position: absolute;
		top: 15px;
		right: 15px;
	}
    .modal-login .checkbox-inline {
        margin-top: 12px;
    }
    .modal-login input[type="checkbox"]{
        margin-top: 2px;
    }
	.modal-login .btn {
        min-width: 100px;
		background: #3498db;
		border: none;
		line-height: normal;
	}
	.modal-login .btn:hover, .modal-login .btn:focus {
		background: #248bd0;
	}
	.modal-login .hint-text a {
		color: #999;
	}
	.trigger-btn {
		display: inline-block;
		margin: 100px auto;
	}

</style>

</head>
<body>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Mytrendin</a>
    </div>
    
    <ul class="nav navbar-nav">
    <?php if (!$user_id) { ?>
      <li><a href="#myModal" data-toggle="modal">Signup</a></li>
      <?php } else{ ?>
    </ul>
       <div class="pull-right nav navbar-nav">Welcome Back, <?php echo $user_name; ?></div><br>
    <span class="pull-right"><a href="#myModal" data-toggle="modal">Logout</a></span>
  <?php } ?>
   

  </div>
</nav>

<div>
<span><?php echo $user_name; ?></span><br>
<span><?php echo $user_id; ?></span><br>
<span><?php echo $user_phone; ?></span><br>
<span><?php echo $user_email; ?></span>

</div>
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
	<div class="modal-dialog modal-login">
		<div class="modal-content">
			<form action="/examples/actions/confirmation.php" method="post">
				<div class="modal-header">				
					<h4 class="modal-title">Signup</h4>
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				</div>
				<div class="modal-body">
                <div class="form-group">
						<label>Name</label>
						<input type="text" class="form-control" id="register_name" required="required">
					</div> 

					<div class="form-group">
						<label>Email</label>
						<input type="text" class="form-control" id="register_email" required="required">
					</div>
					<div class="form-group">
						<div class="clearfix">
							<label>Phone</label>
						</div>
						
						<input type="text" class="form-control" id="register_phone" required="required">
					</div>

                    <div class="form-group">
						<div class="clearfix">
							<label>Password</label>
						</div>
						
						<input type="password" class="form-control" id="register_password" required="required">
                        
					</div>
                    <span id="error_text_phone" style="color: red;"></span>
                    
				</div>
				<div class="modal-footer">
					<label class="checkbox-inline pull-left"><input type="checkbox"> Remember me</label>
					<input type="button" id="register_button" class="btn btn-primary pull-right" value="Register">
				</div>
			</form>
		</div>
	</div>
</div> 

<div id="OTPModal" class="modal fade">
	<div class="modal-dialog modal-login">
		<div class="modal-content">
			<form action="#" method="post">
				<div class="modal-header">				
					<h4 class="modal-title">Verify OTP</h4>
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				</div>
				<div class="modal-body">				
					<div class="form-group">
						<label>Please enter OTP sent to your phone</label>
						<input type="text" class="form-control" id="otp" required="required">
					</div>
					<span id="error_text_otp" style="color: red;"></span>
                    
				</div>
				<div class="modal-footer">
					
					<input type="button" id="verify_button" class="btn btn-primary pull-right" value="Verify Now">
				</div>
			</form>
		</div>
	</div>
</div> 




<!--Register Account-->
 <script>  

 $(document).ready(function(){ 


      $('#register_button').click(function(e){ 
            e.preventDefault();
           
            $('#error_text_phone').text("");
           var email = $('#register_email').val();  
           var phone = $('#register_phone').val();
           var password = $('#register_password').val();
           var name = $('#register_name').val();
          
           
           if(email != '' && phone != '' && password != '')  
           {  
                $.ajax({  
                     url:'signup.php',  
                     method:"POST",  
                     data: {email:email,phone:phone,password:password,name:name}, 
                     beforeSend: function() {
                          $("#register_button").html('Please wait...');
                          $("#register_button").attr("disabled", true);   
                      }, 

                      error:function(data){
 
                         console.log(data); 

                      },
                    
                     success:function(data)  
                     {     
                         alert(data);
                       if(data=='success'){
                           
                           $("#register_button").attr("disabled", false);
                           //$('#otpModal').modal('toggle');
                           $('#myModal').modal('hide');
                           $('#OTPModal').modal('toggle');
                           
                            

                         }else{

                              //alert(data);
                              $('#error_text_phone').text("Email/Phone already exists");
                              $("#register_button").attr("disabled", false);
                              $("#register_button").html('Register');

                         } 
                     }  
                });  
           }  
           else  
           {  
                $('#error_text_phone').text("All Fields are required"); 
           }  
      });  
        
 }); 

 </script>


 <!--Register Account-->


  <!--Verify  Account-->

 <script>  

 $(document).ready(function(){ 
    
      $('#verify_button').click(function(e){ 
            e.preventDefault();

            $('#otp_error').text("");
           var otp = $('#otp').val();  
           var phone =$('#register_phone').val(); 
           //alert(phone);
            

           if(otp != '')  
           {  
                $.ajax({  
                     url:'verifyotp.php',  
                     method:"POST",  
                     data: {otp:otp,phone:phone}, 
                     beforeSend: function() {
                          
                          $("#verify_button").html('Please wait...');
                          $("#verify_button").attr("disabled", true);                       
                          
                      },         
                     success:function(data)  
                     {  
                         alert(data);
                         console.log(data);
                       $("#verify_button").attr("disabled", false);
                         if(data == 'success')
                          {  
                                 $('#login-modal').hide();   
                                  location.reload();

                          }  
                          else  
                          {  
                              $("#verify_button").html('Verify Now');
                              $('#otp_error').text("Incorrect OTP! Try Again"); 
                             
                          }  
                     }  
                });  
           }  
           else  
           {  
                $('#otp_error').text("Please enter OTP"); 
           }  
      });  
        
 }); 

 </script>
 <!--Verify Account-->

    
</body>
</html>

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts