OTP is an effective way of validating users. This type of validation is widely followed by the banking applications, e-commerce software, and many more verticals. In this tutorial, we are going to see how to implement OTP SMS mobile number verification using PHP.
There are various APIs available in the market for sending SMS via an application. In this code, I have used the Textlocal API for sending OTP SMS. Textlocal is one of the popular SMS services. It provides the SMS service for many programming languages. Download the API PHP class to integrate it into our application platform.
In a previous tutorial, we have seen how to verify email and login with OTP authentication using PHP. For verifying a mobile number by sending OTP SMS with the use of Textlocal API, we need to create a Textlocal account and login with to get the API key. This API key is used later while instantiating the API class for sending SMS.
In this example, we use two HTML forms. One is for getting the mobile number and the other is for getting the OTP. By submitting these forms, the AJAX request will be sent to access PHP to send OTP code and to validate it with PHP session data.
This is the landing page that will show a HTML form for getting user’s mobile number to be verified. On submitting the mobile number by clicking the send OTP button, an AJAX code will be executed to request PHP for sending OTP via SMS using the Textlocal API.
<!DOCTYPE html>
<html>
<head>
<title>How to Implement OTP SMS Mobile Verification in PHP with TextLocal</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="error"></div>
<form id="frm-mobile-verification">
<div class="form-heading">Mobile Number Verification</div>
<div class="form-row">
<input type="number" id="mobile" class="form-input"
placeholder="Enter the 10 digit mobile">
</div>
<input type="button" class="btnSubmit" value="Send OTP"
onClick="sendOTP();">
</form>
</div>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="verification.js"></script>
</body>
</html>
This is another HTML form that will be loaded by AJAX after sending the OTP to the user’s mobile number. The user has to submit the received OTP via this form. The generated OTP code is stored in a PHP session variable. This session data will be used for verifying the entered OTP is correct or not.
<div class="error"></div>
<div class="success"></div>
<form id="frm-mobile-verification">
<div class="form-row">
<label>OTP is sent to Your Mobile Number</label>
</div>
<div class="form-row">
<input type="number" id="mobileOtp" class="form-input" placeholder="Enter the OTP">
</div>
<div class="row">
<input id="verify" type="button" class="btnVerify" value="Verify" onClick="verifyOTP();">
</div>
</form>
This is the JavaScript file containing the functions for requesting OTP Sending and Verification PHP code via AJAX. Both of these functions sends the appropriate action parameter to execute suitable PHP code block. The sendOTP() method sends the mobile number and send_otp action params to the PHP file. Similarly, the verifyOTP() method sends the OTP code entered by the user with corresponding action parameter.
function sendOTP() {
$(".error").html("").hide();
var number = $("#mobile").val();
if (number.length == 10 && number != null) {
var input = {
"mobile_number" : number,
"action" : "send_otp"
};
$.ajax({
url : 'controller.php',
type : 'POST',
data : input,
success : function(response) {
$(".container").html(response);
}
});
} else {
$(".error").html('Please enter a valid number!')
$(".error").show();
}
}
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#mobileOtp").val();
var input = {
"otp" : otp,
"action" : "verify_otp"
};
if (otp.length == 6 && otp != null) {
$.ajax({
url : 'controller.php',
type : 'POST',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
}
This is the PHP Controller class which is accessed via AJAX. The class constructor invokes the function for handling mobile verification actions based on the request sent via the AJAX call. This function processes sending OTP to a target mobile and validating OTP entered by the user.
<?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 "send_otp":
$mobile_number = $_POST['mobile_number'];
$apiKey = urlencode('YOUR_API_KEY');
$Textlocal = new Textlocal(false, false, $apiKey);
$numbers = array(
$mobile_number
);
$sender = 'PHPPOT';
$otp = rand(100000, 999999);
$_SESSION['session_otp'] = $otp;
$message = "Your One Time Password is " . $otp;
try{
$response = $Textlocal->sendSms($numbers, $message, $sender);
require_once ("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']);
echo json_encode(array("type"=>"success", "message"=>"Your mobile number is verified!"));
} else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
}
}
}
$controller = new Controller();
?>
This is the output screenshot for the HTML forms to get the mobile number and the OTP code from the user.
Nice.
Thanks Saurabh.
this is good work
Thank you Philip.
it showing error Error: Invalid login details
showing error invalid
Hi Nirbhay,
Do you have Textlocal account and proper API keys?
How to create a textlocal ,it shows some error related to textlocal
Hi Vijay,
You need to buy a plan from Textlocal to use to send SMS.
you can make this for free using firebase, it will give you 10k verification monthly for $0. Can you make a tutorial for it? Regards. or can you contact me to discuss price for it?
Yes, you are right it can be done using Firebase notifications too.
I checked Firebase… Looks interesting.
Did you figure a way to blend Vincy’s code with it ?
nice job
Thank you John.
Good
Thank you Davinder.
code is really good but i recieved otp only in the registed number in textlocal ,when i tried other number it shows that otp is sended but i didn’t recieved any otp
Check in the panel for delivery status.
Can you show us how to implement resend otp with a timer?
Sure Prasad, I will to write on it when time permits.
Hello
I live in Algeria
Does this code work in all countries or only in your country?
Hi Zanki,
It should work irrespective of the country.
Where to get API KEYS??
Hi John,
You need to register with TextLocal and get API keys from them.
Wow nice one
Thank you Jafar.
great work
Appreciate
Thank you.
The code is great
Thank you Eddy.
for me otp is not comming and no error is shown how to resolve it
Vissakan, you need a TextLocal account.