By | May 25, 2021

Mobile Number Verification via OTP SMS using PHP. How to send otp sms using php

One-time passwords, or OTPs, are a quick and easy way to validate a user’s cell number. OTP is often provided to the user’s cell phone through SMS. To authenticate their mobile number, the user must send the verification code. We’ll teach you how to use PHP to build the one-time password (OTP) verification procedure through SMS in this tutorial.

MS Gateway makes it simple to send a text message to a mobile phone number from a script. You may quickly transmit an OTP code to a user’s cellphone phone using the SMS gateway API. The majority of SMS gateway providers allow you to send SMS from your PHP script. We’ll utilise the SMS gateway API in the sample code to deliver OTP SMS from PHP.

To use PHP to perform mobile number verification through OTP SMS, follow the steps below.

  • Make a random code for verification.
  • Send a one-time password (OTP) to the user using SMS gateway API and save it in the database.
  • Check the OTP code and update the database state.
  • Show the user the verification status.

Make a database table.

A table in the MySQL database must be built to contain the OTP code and verification status. In the MySQL database, the following SQL generates a mobile numbers table with some basic fields.

CREATE TABLE `mobile_numbers` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `mobile_number` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `verification_code` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `verified` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=Verified, 0=Not verified',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Class (DBclass.php)

The DB class is responsible for all database operations (fetch, insert, and update). According to your database server credentials, specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

To get, insert, and update OTP data in the database, utilise the following functions.

Connect and choose the database with __construct().
checkRow() – Determines whether any entry in the mobile numbers table exists based on the given criteria. If the object exists, it returns TRUE; otherwise, it returns FALSE.
insert() – Inserts data into the database’s mobile numbers table.

update() – Updates data depending on circumstances in the database’s mobile numbers table.

<?php
/*
 * DB Class
 * This class is used for database related (connect, insert, and update) operations
 
 */
class DB{
    private $dbHost     = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "root";
    private $dbName     = "codexworld";
    private $tblName    = "mobile_numbers";
    
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
    
    /*
     * Returns rows from the database based on the conditions
     * @param string name of the table
     * @param array select, where, order_by, limit and return_type conditions
     */
    public function checkRow($conditions = array()){
        $sql = 'SELECT * FROM '.$this->tblName;
        if(!empty($conditions)&& is_array($conditions)){
            $sql .= ' WHERE ';
            $i = 0;
            foreach($conditions as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $sql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }

        $result = $this->db->query($sql);
        
        return !empty($result->num_rows > 0)?true:false;
    }
    
    /*
     * Insert data into the database
     * @param string name of the table
     * @param array the data for inserting into the table
     */
    public function insert($data){
        if(!empty($data) && is_array($data)){
            $columns = '';
            $values  = '';
            $i = 0;
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $columns .= $pre.$key;
                $values  .= $pre."'".$val."'";
                $i++;
            }
            $query = "INSERT INTO ".$this->tblName." (".$columns.") VALUES (".$values.")";
            $insert = $this->db->query($query);
            return $insert?$this->db->insert_id:false;
        }else{
            return false;
        }
    }
    
    /*
     * Update data into the database
     * @param string name of the table
     * @param array the data for updating into the table
     * @param array where condition on updating data
     */
    public function update($data,$conditions){
        if(!empty($data) && is_array($data)){
            $colvalSet = '';
            $whereSql = '';
            $i = 0;
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $colvalSet .= $pre.$key."='".$val."'";
                $i++;
            }
            if(!empty($conditions)&& is_array($conditions)){
                $whereSql .= ' WHERE ';
                $i = 0;
                foreach($conditions as $key => $value){
                    $pre = ($i > 0)?' AND ':'';
                    $whereSql .= $pre.$key." = '".$value."'";
                    $i++;
                }
            }
            $query = "UPDATE ".$this->tblName." SET ".$colvalSet.$whereSql;
            $update = $this->db->query($query);
            return $update?$this->db->affected_rows:false;
        }else{
            return false;
        }
    }
}

Form to Verify Your OTP

An HTML form is first provided to allow the user to provide their mobile phone number. Following the entry of the phone number, the OTP input area appears for entering the verification code.

<!-- Display status message -->
<?php echo !empty($statusMsg)?'<p class="'.$statusMsg['status'].'">'.$statusMsg['msg'].'</p>':''; ?>

<!-- OTP Verification form -->
<form method="post">
    <label>Enter Mobile No</label>
    <input type="text" name="mobile_no" value="<?php echo !empty($recipient_no)?$recipient_no:''; ?>" <?php echo ($otpDisplay == 1)?'readonly':''; ?>/>
    
    <?php if($otpDisplay == 1){ ?>
    <label>Enter OTP</label>
    <input type="text" name="otp_code"/>
    <a href="javascript:void(0);" class="resend">Resend OTP</a>
    <?php } ?>
    <input type="submit" name="<?php echo ($otpDisplay == 1)?'submit_otp':'submit_mobile'; ?>" value="VERIFY"/>
</form>

OTP Submission and Verification

The phone number and OTP are validated via SMS gateway using PHP after submission.

  • sendSMS() is a PHP-based custom function for sending SMS over the SMS Gateway API.
  • To handle database-related tasks, load and initialise the database class.


When a user submits their mobile number, the following events occur.

  • Using PHP’s rand() function, generate a random verification code.
    To see if any records in the database have the same mobile number, use the DB class’s checkRow() function.
    If the mobile number exists, use the DB class’s update() function to update the database’s sole verification code.
  • If the mobile number does not exist, use the DB class’s insert() function to input OTP data into the database.
    Use the sendSMS() method to send an OTP code to the user through SMS.
    OTP entry will be allowed once the OTP SMS is issued successfully.

When the user submits the OTP, the following occurs.

Check the OTP to see if the user has entered the right verification code.
In the database, update the verification status.

<?php
function sendSMS($senderID, $recipient_no, $message){
    // Request parameters array
    $requestParams = array(
        'user' => 'codexworld',
        'apiKey' => 'dssf645fddfgh565',
        'senderID' => $senderID,
        'recipient_no' => $recipient_no,
        'message' => $message
    );
    
    // Merge API url and parameters
    $apiUrl = "http://api.example.com/http/sendsms?";
    foreach($requestParams as $key => $val){
        $apiUrl .= $key.'='.urlencode($val).'&';
    }
    $apiUrl = rtrim($apiUrl, "&");
    
    // API call
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    // Return curl response
    return $response;
}

// Load and initialize database class
require_once 'DB.class.php';
$db = new DB();
        
$statusMsg = $receipient_no = '';
$otpDisplay = $verified = 0;

// If mobile number submitted by the user
if(isset($_POST['submit_mobile'])){
    if(!empty($_POST['mobile_no'])){
        // Recipient mobile number
        $recipient_no = $_POST['mobile_no'];
        
        // Generate random verification code
        $rand_no = rand(10000, 99999);
        
        // Check previous entry
        $conditions = array(
            'mobile_number' => $recipient_no,
        );
        $checkPrev = $db->checkRow($conditions);
        
        // Insert or update otp in the database
        if($checkPrev){
            $otpData = array(
                'verification_code' => $rand_no
            );
            $insert = $db->update($otpData, $conditions);
        }else{
            $otpData = array(
                'mobile_number' => $recipient_no,
                'verification_code' => $rand_no,
                'verified' => 0
            );
            $insert = $db->insert($otpData);
        }
        
        if($insert){
            // Send otp to user via SMS
            $message = 'Dear User, OTP for mobile number verification is '.$rand_no.'. Thanks CodexWorld';
            $send = sendSMS('CODEXW', $recipient_no, $message);
            
            if($send){
                $otpDisplay = 1;
            }else{
                $statusMsg = array(
                    'status' => 'error',
                    'msg' => "We're facing some issue on sending SMS, please try again."
                );
            }
        }else{
            $statusMsg = array(
                'status' => 'error',
                'msg' => 'Some problem occurred, please try again.'
            );
        }
    }else{
        $statusMsg = array(
            'status' => 'error',
            'msg' => 'Please enter your mobile number.'
        );
    }
    
// If verification code submitted by the user
}elseif(isset($_POST['submit_otp']) && !empty($_POST['otp_code'])){
    $otpDisplay = 1;
    $recipient_no = $_POST['mobile_no'];
    if(!empty($_POST['otp_code'])){
        $otp_code = $_POST['otp_code'];
        
        // Verify otp code
        $conditions = array(
            'mobile_number' => $recipient_no,
            'verification_code' => $otp_code
        );
        $check = $db->checkRow($conditions);
        
        if($check){
            $otpData = array(
                'verified' => 1
            );
            $update = $db->update($otpData, $conditions);
            
            $statusMsg = array(
                'status' => 'success',
                'msg' => 'Thank you! Your phone number has been verified.'
            );
            
            $verified = 1;
        }else{
            $statusMsg = array(
                'status' => 'error',
                'msg' => 'Verification code incorrect, please try again.'
            );
        }
    }else{
        $statusMsg = array(
            'status' => 'error',
            'msg' => 'Please enter the verification code.'
        );
    }
}
?>

Verification Status

The user will see a status message if the OTP is successfully validated.

<!-- Display status message -->
<?php echo !empty($statusMsg)?'<p class="'.$statusMsg['status'].'">'.$statusMsg['msg'].'</p>':''; ?>

<?php if($verified == 1){ ?>
    <p>Mobile No: <?php echo $recipient_no; ?></p>
    <p>Verification Status: <b>Verified</b></p>
<?php } ?>

Category: Php

Leave a Reply

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