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. how to send sms using textlocal api in php
The following process will be followed to implement mobile number verification via OTP SMS using PHP
Table of Contents
Create Database and Table by 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 file in 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
<!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
<!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>
<?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
<?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"; } } ?>
Create dashboard or Profile File after verify OTP
<?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
<?php session_start(); session_destroy(); unset($_SESSION['MOBILE']); unset($_SESSION['NAME']); header("Location:login.php"); ?>
very useful tutorial thanks