Dj Techblog

A blog on web development

Otp sms in php for mobile number verification by using Textlocal

Last modified on June 22, 2022
Mobile number verification by otp sms in php using Textlocal

Basically there are two ways we can verify a user's online identity.

  1. Mobile Number verification
  2. Email verification

OTP sms in php is used for mobile number verification where we generate a unique 6 digit code known as OTP and send it to user mobile number via sms as a one time verification code using Textlocal bulk sms gateway. Otp sms verification in php can be used in variety of websites for user registrations using mobile number.

You can watch the Youtube video below in local language to better understand how thing works.

There are lots of bulk sms gateway available. These gateways are used for sending bulk sms like promotional sms, transactional sms. Promotional sms are used for marketing. But transactional messages are generally used for user indentification via OTP verification. We use Textlocal's API to send OTP SMS and verify user mobile number.

Textlocal is one of bulk sms provider in India. To register with Textlocal follow this link. Textlocal bulk sms service.

There is one another bulk sms provider easy to use, you should definitely try Fast2sms bulk sms service.

For SMS OTP verification in php, follow these steps :

  1. Go to Textlocal and create an account.
  2. Generate API key in their website for free.
  3. Download the Textlocal API from their website.
  4. Now copy the codes provided here and paste in into your server or localhost.
  5. Paste your generated api key in appropriate place in the code.
  6. Now you are ready to test the code.

We need these files to test our code :

  • index.html          // This file takes name and mobile number as input.
  • script.js         // this javascript file will be called when we hit send otp button in regsiter.php file.
  • server.php         // this file contains two switch cases one for sending otp and another for verifying otp
  • otp-verification-form.html    // This file takes OTP as input which you receive through sms.
  • textlocal.class.php         //this API file contains all the functions necessary to send sms, it is being called by server.php.
  • style.css                       // For styling.

Get user mobile number to send OTP



In the landing page index.html we enter two inputs name and mobile number and hit Get OTP button.

index.html

<!DOCTYPE html>
<html>
<head>
<title>How to integrate textlocal for mobile number verification using otp sms</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="script.js"></script>

</head>
<body>
	<div class="container w3-card">
		<div class="err"></div>
		<form id="mobile-number-verification">
			<div class="mobile-heading">Mobile Number Verification</div>
			<div class="mobile-row">
			    <inpuet typ="text" id="name" class="mobile-input" placeholder="Enter your name">
			    <br>
			    <br>
				<input type="number" id="mobile" class="mobile-input" placeholder="Enter the 10 digit mobile number">
			</div>
			<div id="loading-image">
			<img src="ajax-loader.gif" alt="ajax loader">
			</div>
            <input type="button" class="mobileSubmit" value="Get OTP"onClick="getOTP();">
		</form>
	</div>
	
</body>
</html>
landing page form

Javascript function makes an ajax request to the server to send otp



On clicking the Get OTP button on landing page, a javascript function getOTP() is called. It stores mobile number and name entered by user in a variable and makes an ajax POST request to the server.

script.js

function getOTP() {
$(".err").html("").hide();
var number = $("#mobile").val();
var name = $("#name").val();
if (number.length == 10 && number != null) {
	var user_input = {
	"mobile_number" : number,
	"name" : name,
	"action" : "get_otp"
};
$('#loading-image').show();
$.ajax({
    url : 'server.php',
    type : 'POST',
    data : user_input,
	success : function(response) {
	  $(".container").html(response);
	},
	complete: function(){         
	  $('#loading-image').hide();
    }
	});
	} 
	else {
		$(".err").html('Please enter a valid number!')
		$(".err").show();
	}
}

function verifyOTP() {
	$(".error").html("").hide();
	$(".success").html("").hide();
	var otp = $("#mobileOtp").val();
	var user_input = {
		"otp" : otp,
		"action" : "verify_otp"
	};
	if (otp.length == 6 && otp != null) {
	    $('#loading-image').show();
		$.ajax({
		 url : 'server.php',
		 type : 'POST',
		 dataType : "json",
		 data : user_input,
		 success : function(response) {
			$("." + response.type).html(response.message)
			$("." + response.type).show();
			$("#mobile-verification").html("").hide();
		 },
		 complete: function(){
             $('#loading-image').hide();
         },
		 error : function() {
			 alert("Error");
		}
		});
	} else {
		$(".err").html('You have entered wrong OTP.')
		$(".err").show();
	}
}

Server generates otp and forwards to mobile number using Textlocal API



The server receives the request from the client and checks the database whether the mobile number exists or not. If a mobile number is already registered it responds with an error. Otherwise, it generates a random otp and stores it in a session variable, and forwards the otp to the user mobile number.
After that server responds with a otp-verification-form.php page to the client for the request client has made.

How to send otp sms in php?

Generating otp in php is very simple. We need to use php rand() function to generate otp in php. rand() is a function which takes two parameters, and generates a random number. The two parameters basically specify a range, that is the upper limit and lower limit. Say, you want to generate a OTP of 6 digits so you can provide two range 200000 and 999999. The generated number will always be between 200000 and 999999. After the OTP is generated we send it to the mobile number via a sms gateway.

server.php

<?php
session_start();
error_reporting(E_ALL & ~ E_NOTICE);
require ('textlocal.class.php');

class Controller
{
    function __construct() {
        $this->processMobileVerification();
    }
    function processMobileVerification()
    {
     switch ($_POST["action"]) {
     case "get_otp":
                
        $mobile_number = $_POST['mobile_number'];
        $name = $_POST['name'];
        $db = mysqli_connect('localhost', 'your user name', '(your password)', 'your database');
        $user_check_query = "SELECT * FROM reg_user WHERE mobile='$mobile_number' LIMIT 1";
 		$result =  mysqli_query($db, $user_check_query);
  		if ($result === FALSE) {
 		  die(mysqli_error($connect));
		}
  		$user = mysqli_fetch_assoc($result);
  		if($user)
  		{
  		if ($user['mobile'] === $mobile_number) 
  		{
  		  echo json_encode(array("Mobile Number already Exists. Enter another."));
  		  exit;
    	}
  		}
        $apiKey = urlencode('put your api key here');
        $Textlocal = new Textlocal(false, false, $apiKey);
        $numbers = array($mobile_number);
        $sender = 'TLTEST';
        $otp = rand(100000, 999999);
        $_SESSION['session_otp'] = $otp;
        $_SESSION['mobile_number'] = $mobile_number;
        $_SESSION['name'] = $name;
        $message = "Your otp is " . $otp;
        try{
          $response = $Textlocal->sendSms($numbers, $message, $sender);
          require_once ("otp-verification-form.php");
          exit();
        }catch(Exception $e){
         die('Error: '.$e->getMessage());
        }
        break;
                
    case "verify_otp":
        $otp = $_POST['otp'];
        if ($otp == $_SESSION['session_otp']) 
        {
            unset($_SESSION['session_otp']);
            $mobile = $_SESSION['mobile_number'];
            $name = $_SESSION['name'];
           	unset($_SESSION['mobile_number']); 
           	unset($_SESSION['name']);
            $db = mysqli_connect('localhost', 'your user name', '(your password)', 'your database');
            $password = md5($otp);    
            $query =  "INSERT INTO reg_user ( fname,mobile,password) VALUES( '$fname','$mobile','$password')";
  			$result1 = mysqli_query($db, $query);
  			if ($result === FALSE) 
  			{
  			   die(mysqli_error($connect));
  			   echo json_encode(array("type"=>"error", "message"=>"Mobile number registration failed."));
  			   exit;
 			}

            $apiKey = urlencode('your api key');
            $Textlocal = new Textlocal(false, false, $apiKey);
            $numbers = array($mobile);
            $sender = 'TLTEST';
            $message = "Welcome. Your Registration is successful. Login to your Account and Update your details. Your password is " . $otp;
            try
            {
                	
              $Textlocal->sendSms($numbers, $message, $sender);
              echo json_encode(array("type"=>"success", "message"=> "Mobile number is Registered. Password has been sent to registered Mobile Number. Login to fillup the details" ));
              exit();
            }
            catch(Exception $e)
            {
              die('Error: '.$e->getMessage());
            }
            }
            else{
                 echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
            }
            break;
        }
    }
}
$server = new Controller();
?>
                             

Recommended read,

Make otp expire after certain minutes

send OTP to the server for validation



On entering otp When the user hits on the Verify OTP button a function is called which checks the length of the otp field, if it matches the desired length, it is sent to the server making an ajax request. On receiving the otp server matches it with the self copy of otp, which is stored in a session variable. If a match occurs server responds positively, otherwise responds with an error message.

otp-verification-form.html

<div class="err"></div>
<div class="success"></div>
<div class="container">
<form id="mobile-verification">
	<div class="mobile-row">
		<label>OTP is sent to Your Mobile Number</label>		
	</div>
	<div class="mobile-row">
		<input type="number"  id="mobileOtp" class="mobile-input" placeholder="Enter the OTP">	
	</div>
    <div id="loading-image">
		<img src="ajax-loader.gif" alt="ajax loader">
		</div>
	<div class="mobile-row">
		<input id="verify" type="button" class="btnVerify" value="Verify" onClick="verifyOTP();">		
	</div>
</form>
</div>

Download the style.css file from here.
Download the textLocal api class from their official website.

If you face any issue while implementing the code, you can mail me. Thanks for patient reading.

If this article helps you, support me by sharing this.

Published on Oct 8, 2020


Ad section
Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.