PHP Registration Form with Mobile OTP Verification Example

Today we are going to learn PHP Registration Form with Mobile OTP Verification Example. This tutorial will cover on PHP Registration Form with Mobile OTP Verification with Example with the use of fast2sms.

OTP Verification verifies Email Address/Mobile Number of users by sending OTP verification code during registration, login and contact form submissions. It removes the possibility of users registering with fake Email Address/Mobile Number by enabling OTP Verification.

Also Read: How to Remove a Specific Element From an Array in PHP

File Structures:

File Structures - PHP Registration Form with Mobile OTP Verification Example
File Structures

Steps for PHP Registration Form with Mobile OTP Verification Example:

  • Step 1: Create Database and Table
  • Step 2: Create Connection to Database
  • Step 3: Create Index PHP File
  • Step 4: Create Registration PHP File
  • Step 5: Create Verification PHP File
  • Step 6: Create OTP PHP File
  • Step 7: Create Logout PHP File
  • Step 8: Testing
  • Step 9: Conclusion

Also Read: Upload Images to Server PHP Tutorial (2022)

Step 1: Create Database and Table

Firstly, we are going to create a database and a table. Open phpmyadmin and create new database with name “otp_app“.

Creating database
Creating database

After that run the following query to create a users table.

CREATE TABLE users(
    id INT AUTO_INCREMENT NOT NULL,
    fullName VARCHAR(50) NOT NULL,
    username VARCHAR(255) NOT NULL,
    mobile bigint(11) NOT NULL,
    otp INT(10) NOT NULL,
    password VARCHAR(50) NOT NULL,
    verification_status INT(3) NOT NULL,
    primary key (id)
);
Creating Table
Creating Table

Step 2: Create Connection to Database

Now create a connection.php inside our project file and add the following code into it.

<?php 
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "otp_app";
    $conn = new mysqli($servername,$username,$password,$dbname);
    if($conn->connect_error){
        die ('connection faild:'.$conn->connect_error);
    }
?>

Change $servername, $username, $password, $dbname accordingly.

Also Read: Integration PayPal Payment Gateway in PHP

Step 3: Create Index PHP File

Now we are going to create a index.php and enter the following into it.

<?php 
    session_start();
    require ('connection.php');
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PHP Registration Form with Mobile OTP Verification Example - LaravelTuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container-fluid mt-3">
        <div class="card" style="height:590px;">
            <div class="card-header text-center">
                <h3>PHP Registration Form with Mobile OTP Verification Example - LaravelTuts.com</h3>
            </div>
            <div class="card-body">
                <nav class="navbar navbar-expand-lg navbar-light bg-light">
                    <a class="navbar-brand " href="#">LaravelTuts</a>
                    <div class="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                            <li class="nav-item">
                                <a class="nav-link" href="#">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#">about us</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#">contect us</a>
                            </li>
                        </ul>
                    </div>
                    <form class="justify-content-end">
                        <?php 
                            if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']==TRUE) {
                                echo "<a href='logout.php' class='btn btn-danger'>LOGOUT</a>";
                            }else{
                                echo "<button type='button' class='btn btn-success m-1' data-bs-toggle  ='modal' data-bs-target='#loginModal'>Login</button>
                                <button type='button' class='btn btn-danger m-1' data-bs-toggle='modal' data-bs-target='#RegisterModal'>Register</button>";
                            }
                         ?>
                    </form>
                </nav>
                    <?php 
                        if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']==TRUE) {
                            echo "<h1 class='text-center mt-5 pt-5'>Welcome to this LaravelTuts.com, you are verify!</h1>";
                        }
                    ?>
            </div>
        </div>
        
        <div class="modal fade" id="loginModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="loginModalLabel">Login</h3>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form action="registration.php" method="post">
                        <div class="modal-body">
                            <div class="mb-3">
                                <label>Mobile : </label>
                                <input type="number" name="moblie_number" class="form-control" placeholder="Mobile">
                            </div>
                            <div class="mb-3">
                                <label>Password : </label>
                                <input type="password" name="password" class="form-control" placeholder="Password">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <input type="submit" name="login" class="btn btn-primary">
                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="modal fade" id="RegisterModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="RegisterModalLabel">Register</h3>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form action="registration.php" method="post">
                        <div class="modal-body">
                            <div class="mb-3">
                                <label>Full Name : </label>
                                <input type="text" name="fullName" class="form-control" placeholder="Full Name">
                            </div>
                            <div class="mb-3">
                                <label>User Name : </label>
                                <input type="text" name="username" class="form-control" placeholder="User Name">
                            </div>
                            <div class="mb-3">
                                <label>Mobile : </label>
                                <input type="number" placeholder="Mobile number" name="number" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label>Password : </label>
                                <input type="password" name="password" class="form-control" placeholder="Password">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <input type="submit" name="register" class="btn btn-primary">
                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Also Read: Drag & Drop Reorder Images in PHP (2022)

Step 4: Create Registration PHP File

Before creating registration file we need create a account fast2sms.com and get the API. First create a new account and following the below screenshot to get the API.

fast2sms API Key
fast2sms API Key

Note: You need to add minimum fund to start working with it. Check there website for more details.

So now, create a registration.php file inside a project folder and enter the following code.

<?php 
    require ('connection.php');
    session_start();
    if (isset($_POST['login'])) {
        
        $moblie_number =$_POST['moblie_number'];
        $password_login =$_POST['password'];
        $sql="SELECT * FROM users WHERE mobile = '$moblie_number' AND password = '$password_login' AND verification_status = '1'";
        $result = $conn->query($sql);
        
        if ($row = $result->fetch_assoc()) {
            $_SESSION['logged_in']=TRUE;
            $_SESSION['mobile']=$row['mobile'];
            header('location:index.php');
        }else{
            echo "
                <script>
                    alert('please verify your mobile!!');
                    window.location.href='index.php'
                </script>";
        } 
    }
    if (isset($_POST['register'])) {
            
        $fullName =$_POST['fullName'];
        $username =$_POST['username'];
        $no =$_POST['number'];
        $password =$_POST['password'];
        $otp = rand(1111,9999);
        if(preg_match("/^\d+\.?\d*$/",$no) && strlen($no)==10){
            $user_exist_query="SELECT * FROM users WHERE mobile= '$no'";
            $result = $conn->query($user_exist_query);
            if ($result) {
                
                if ($result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    
                    if ($row['username'] === $username) {
                        echo "
                            <script>
                                alert('Mobile no alredy register!');
                                window.location.href='index.php'
                            </script>";
                    }
                
                }else{
                    
                    $query ="INSERT INTO `users`(`fullName`, `username`, `mobile`, `password`,`otp`, `verification_status`) VALUES ('$fullName','$username','$no','$password','$otp','0')";
                        
                    if ($conn->query($query)===TRUE) {

                        $fields = array(
                            "variables_values" => "$otp",
                            "route" => "otp",
                            "numbers" => "$no",
                        );
                        
                        $curl = curl_init();
                        
                        curl_setopt_array($curl, array(
                          CURLOPT_URL => "https://www.fast2sms.com/dev/bulkV2",
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_ENCODING => "",
                          CURLOPT_MAXREDIRS => 10,
                          CURLOPT_TIMEOUT => 30,
                          CURLOPT_SSL_VERIFYHOST => 0,
                          CURLOPT_SSL_VERIFYPEER => 0,
                          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                          CURLOPT_CUSTOMREQUEST => "POST",
                          CURLOPT_POSTFIELDS => json_encode($fields),
                          CURLOPT_HTTPHEADER => array(
                            "authorization: Your-Api-Key",
                            "accept: */*",
                            "cache-control: no-cache",
                            "content-type: application/json"
                          ),
                        ));
                        
                        $response = curl_exec($curl);
                        $err = curl_error($curl);
                        
                        curl_close($curl);
                        
                        if ($err) {
                            echo "cURL Error #:" . $err;
                        } else {
                            $data = json_decode($response);
                            $sts = $data->return;
                            if ($sts == false) {
                                echo "
                                <script>
                                    alert('Your OTP is not send.');
                                    window.location.href='index.php'
                                </script>";
                            }else{
                                echo "
                                <script>
                                    alert('Register Successful. Please Check your text message and verify your account.');
                                    window.location.href='verification.php?mobile=$no'
                                </script>";
                            }
                        }
                    }else{
                        echo "
                            <script>
                                alert('Something went wrong!!!');
                                window.location.href='index.php'
                            </script>";
                    }
                }
            }else{
                echo "
                <script>
                    alert('donot enter in if');
                    window.location.href='index.php'
                </script>";
            }
        }else{
            echo "
                <script>
                    alert('Invalid Mobile Number!!');
                    window.location.href='index.php'
                </script>";
        }
    }
 ?>

Also Read: PHP Chunk File Upload using JavaScript

Step 5: Create Verification PHP File

Now create a verification.php file inside the project folder and enter the below code.

<?php 
    $mobile_number = $_GET['mobile'];
 ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Verify Mobile Number - LaravelTuts.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="card mt-4">
            <div class="card-header">
                <h1 class="text-center">Verify Mobile Number - LaravelTuts.com</h1>
            </div>
            <div class="card-body">
                <form action="otp.php" method="post">
                    <div class="mt-4">
                        <label for="mobile">Mobile</label>
                        <input type="number" name="moblie_no" class="form-control" placeholder="Enter mobile no" value="<?php echo $mobile_number;?>">
                    </div>
                    
                    <div class="mt-4">
                        <label for="otp">OTP</label>
                        <input type="number" name="otp" class="form-control" placeholder="Enter OTP">
                    </div>
                    <div class="text-center mt-4">
                        <input type="submit" name="verify" value="verify" class="btn btn-primary">
                    </div>
                </form>         
            </div>
        </div>
    </div>
</body>
</html>

Also Read: How to Login with Google in PHP

Step 6: Create OTP PHP File

So now, create otp.php file inside project folder and enter the below code.

<?php 
    require ('connection.php');
    if (isset($_POST['verify'])){
        
        $mobile_number = $_POST['moblie_no'];   
        $otp = $_POST['otp'];   
        $sql="SELECT * FROM users WHERE mobile = '$mobile_number' AND otp = '$otp'";
        $result = $conn->query($sql);
        if ($result) {
            
            if ($result->num_rows == 1) {
                
                $row = $result->fetch_assoc();
                $fetch_mobile = $row['mobile'];
                    
                if ($row['verification_status'] == 0) {
                    $update = "UPDATE users SET verification_status='1' WHERE mobile = '$fetch_mobile'";
                    
                    if ($conn->query($update)===TRUE) {
                    echo "
                        <script>
                            alert('Mobile number verification successful');
                            window.location.href='index.php'
                        </script>"; 
                    }else{
                    echo "
                        <script>
                            alert('Query can not run');
                            window.location.href='verification.php'
                        </script>";
                    }
                }else{
                    echo "
                        <script>
                            alert('Mobile already been register');
                            window.location.href='verification.php'
                        </script>";
                }
            }
        }   
    }else{
        echo "
            <script>
                alert('Server Down!!');
            </script>";
    }
?>

Step 7: Create Logout PHP File

Now, Finally we are creating a logout.php and enter the following code inside the file as show below.

<?php 
    session_start();
    session_unset();
    session_destroy();
    header("location:index.php");
?>

Also Read: How to Create a Login Form in PHP Example

Step 8: Testing

At last, we are going to test our PHP application. Open the URL as show below in any web browser and register a new user.

http://localhost/otp_app/index.php

Note: Change the folder name if you had a different name.

Previews:

Registering new User - PHP Registration Form with Mobile OTP Verification Example
Registering new User
OPT Sent Successfully - PHP Registration Form with Mobile OTP Verification Example
OPT Sent Successfully
Verify OTP - PHP Registration Form with Mobile OTP Verification Example
Verify OTP
Successfully Verify Mobile Number - PHP Registration Form with Mobile OTP Verification Example
Successfully Verify Mobile Number
Database Update with verify mobile number - PHP Registration Form with Mobile OTP Verification Example
Database Update with verify mobile number
Dashboard after Account Login - PHP Registration Form with Mobile OTP Verification Example
Dashboard after Account Login

Step 9: Conclusion

Today, We had learn PHP Registration Form with Mobile OTP Verification Example. Hope this tutorial helped you with learning PHP. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: How to Upload Multiple Files/Images in MySQL Database with PHP 8

3 Comments

Leave a Reply