Email OTP Verification using PHP in Live Server

07 Apr, 2022
The task is to create and design a sign-up and login form. In the sign-up form, the user will sign-up with a custom username and password and a valid email then the user will receive an OTP through the email, and after successful verification of OTP user account will be created and data will be stored in MySQL database, and then the user will be redirected to the home page. In the login form, the user can login with the username and password that the user entered while creating the new account. 
Note: We will implement this whole thing in a live server, anyone can implement this to their own local server like XAMPP, but the email verification part will not work in the local server.
Approach for Sign-up Form:
The first task is to create a MySQL server Database and a Table according to our requirements.
We connect our MySQL server Database using PHP mysqli_connect() function that takes four arguments, i.e. our “servername”, “username”, “password” and “database”.
After entering all the details of the user, we will generate a 6 digit random number using PHP rand() function and store it to the local session variable then send it to the user email using PHP mailer function.
When the user enters the OTP, we will verify it with the OTP stored in session if these match then store redirect the user to the home page.
Create a new table with the name as username the user provided to store the email and password of that user.
Approach for Log-in Form:
Connect to the database as described above, then check the credential provided by the user, if they match with the data stored in the database then redirect the user to the home page else show the related error.
PHP code for registration form: register.php 
PHP
<!DOCTYPE html><html lang="en"> <?php    session_start();    $otp=$_SESSION["OTP"];    if(isset($_SESSION["logged-in"])){        header("Location:profile.php");    }    $username="sign up";    $login_btn="Login";    if(isset($_SESSION["username"])){        $username=$_SESSION["username"];        $login_btn="Logout";    }    if($_SERVER["REQUEST_METHOD"]=="POST"){        $con=mysqli_connect('localhost',            'database_username',            'database_pass','database_name');         if(!$con)            echo ("failed to connect to database");        $username1=$_POST['username'];        $prefix="_";        $username=$prefix.$username1;        $password=$_POST['Password'];        $repassword=$_POST['RePassword'];        $email1=$_POST['Email'];        $email=strval($email1);        if($password!=$repassword){            echo("<script>alert('password not matches')</script>");        }        else{            if(strlen($password)<8){                echo(    "<script>alert('password length must be atleast 8')</script>");            }            else{                $query="insert into 1_user(username,email,password)                        values('$username','$email','$password')";                 $sql = "SELECT id,username, password FROM 1_user";                $result = $con->query($sql);                $username_already_exist=false;                $email_already_exist=false;                 // Checking if user already exist                if(($result->num_rows)> 0){                    while($row = $result->fetch_assoc()) {                         // echo "<br> id: " . $row["id"] .                            " - username= " . $row["username"] .                            " password= " . $row["password"] . "<br>";                         if($row["username"]==$username){                               $username_already_exist=true;                            break;                        }                        if($row["email"]==$email){                               $email_already_exist=true;                            break;                        }                    }                }                 // echo($ok);                if($username_already_exist==false){                     // This is my hosting mail                    $from ="support@libraryatcoer.tk";                    $to=$email;                    $subject="verify-account-otp";                     // Generating otp with php rand variable                    $otp=rand(100000,999999);                    $message=strval($otp);                    $headers="From:" .$from;                    if(mail($to,$subject,$message,$headers)){                        $_SESSION["username"]=$username;                        $_SESSION["OTP"]=$otp;                        $_SESSION["Email"]=$email;                        $_SESSION["Password"]=$password;                        $_SESSION["registration-going-on"]="1";                        header("Location:verify-otp.php");                    }                    else                        echo("mail send faild");                }                else{                    echo(            "<script>alert('username  already taken')</script>");                }            }        }    }?>  <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Document</title>    <link rel="stylesheet" type="text/css"        href="css/style.css" media="screen" />    <!--  adding bootstrap  -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous">    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script>         <div class="nav-bar">        <div class="title">            <h3>welcome to my website</h3>        </div>    </div></head> <body>    <form class="form-register"        action="register.php" method="POST">        <div class="form-group">            <label>username</label>            <input type="text" class="form-control"                name="username" id="username"                aria-describedby="emailHelp"                placeholder="username" required>        </div>        <div class="form-group">            <label>Email</label>            <input type="email" class="form-control"                name="Email" id="Email"                placeholder="Email" required>        </div>        <div class="form-group">            <label>Password</label>            <input type="password" class="form-control"                name="Password" id="Password"                placeholder="Password" required>        </div>        <div class="form-group">            <label>Password</label>            <input type="password"                class="form-control" name="RePassword"                id="RePassword" placeholder="RePassword"                required>        </div>         <button type="submit"            class="btn btn-primary btn-lg">            Register        </button>         <button type="button"            class="btn btn-warning btn-lg"            id="login-button">            Already Registered        </button>    </form>         <script>        $("#login-button").click(function () {            window.location.replace("index.php");        });    </script></body> </html>
PHP code to send and verify OTP: verify-otp.php
PHP
<!DOCTYPE html><html lang="en">    <?php        session_start();             // Retrieving otp with session variable        $otp=$_SESSION["OTP"];    ?> <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Document</title>    <link rel="stylesheet" type="text/css"        href="css/style.css" media="screen" />     <!--  Adding bootstrap  -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous">     <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>         <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script>         <div class="nav-bar">        <div class="title">            <h3>welcome to my website</h3>        </div>    </div></head> <body>    <form class="form-login">        <div class="form-group">            <input type="text" class="form-control"                name="otp" id="OTP"                aria-describedby="emailHelp"                placeholder="Enter OTP" required>        </div>         <button type="button"            class="btn btn-primary btn-lg"            id="verify-otp">            verify otp        </button>    </form>     <script>        $("#resend-otp").click(function () {            window.location.replace("resend-otp.php");        });        $("#verify-otp").click(function () {             // window.location.replace("index.php");            var otp1 = document.getElementById("OTP").value;             // alert(otp1);            var otp2 = ("<?php echo($otp)?>");                         // alert(otp2);            if (otp1 == otp2) {                window.location.replace("logged-in.php");            }            else {                alert("otp not matches")            }        });    </script></body> </html>
PHP code to resend OTP in case of OTP not received: resend-otp.php
PHP
<!DOCTYPE html><html lang="en"> <?php     session_start();         // ini_set('dispaly_errors',1);    // error_reporting(E_ALL);    $from ="support@libraryatcoer.tk";    $to=$_SESSION["Email"];    $subject="verify-account-otp";    $otp=rand(100000,999999);    $message=strval($otp);    $headers="From:" .$from;             if(mail($to,$subject,$message,$headers)){        $_SESSION["OTP"]=$otp;        header("Location:verify-otp.php");    }    else        echo("mail send faild");?> <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Document</title>    <link rel="stylesheet" type="text/css"        href="css/style.css" media="screen" />     <!--  Adding bootstrap  -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous">     <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>         <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script>         <div class="nav-bar">        <div class="title">            <h3>welcome to coer library</h3>        </div>    </div></head> <body>    <div class="form">        <form action="register.php" method="POST">            <label><b>Register To MY website</b></label>            <hr class="first">            <label><b>Coer-ID</b></label>            <input type="text" name="Coer-ID"                placeholder="Coer-ID" required id="Coer-ID"                class="float-left1">            <br><br>             <label><b>Email</b></label>            <input type="email" name="Email"                placeholder="Email" required id="Email"                class="float-left1">            <br><br>             <label><b>Password </b> </label>            <input type="Password" name="Password"                placeholder="Password" required id="Password"                class="float-left1">            <br><br>             <label><b>RePassword </b> </label>            <input type="Password" name="RePassword"                placeholder=" Re Type Password"                required id="Repassword"                class="float-left1">            <br><br>             <button type="submit" name="login"                value="login" id="register-button">                create account            </button>            <br><br>        </form>    </div></body> </html>
After successful OTP verification inserting user data to table 1_user:
Table schema, each row has these 4 columns: 
id (int data type as primary key)
username (text data type)
email (text data type)
password (text data type) 
 PHP code for login form also the default page: index.php
PHP
<!DOCTYPE html><html lang="en"><?php    $message=    "logged in successfully...redirecting to home page";     session_start();    if(isset($_SESSION["logged_in"])){        header("Location:profile.php");    }     if($_SERVER["REQUEST_METHOD"]=="POST"){        $con=mysqli_connect('localhost',            'database_username',            'database_pass','database_name');         if($con);        else            echo "failed to connect to database";        $username1=$_POST['username'];        $prefix="_";        $username=$prefix.$username1;        $password=$_POST['Password'];         $sql = "SELECT id,username, password FROM 1_user";        $result = $con->query($sql);         if ($result->num_rows > 0) {            $fnd=0;            while($row = $result->fetch_assoc()) {                 /* echo "<br> id: ". $row["id"].                " - username= ". $row["username"].                " password= " . $row["password"] . "<br>"; */                 if($row["username"]==$username and                    $row["password"]==$password) {                                            $_SESSION["username"] = $username;                    $_SESSION["registration-going-on"]="0";                    $fnd=1;                    $_SESSION["logged_in"]="1";                    echo '<div class="alert alert-success"                        role="alert">'.$message.'</div>';                     echo"<script>setTimeout(\"location.href = 'profile.php';\",3000);</script>";                }            }            if($fnd==0)                echo("<script>alert('username password not matches')</script>");         }        else {            echo("<script>alert('username password not matches')</script>");        }        $con->close();    }?> <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Document</title>     <link rel="stylesheet" type="text/css"        href="css/style.css" media="screen" />     <!--  Adding bootstrap  -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous">     <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>         <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script>         <div class="nav-bar">        <div class="title">            <h3>welcome to my website</h3>        </div>    </div></head> <body>    <form class="form-login" action="index.php" method="POST">        <div class="form-group">            <label>username</label>            <input type="text" class="form-control"                name="username" id="username"                aria-describedby="emailHelp"                placeholder="username" required>        </div>         <div class="form-group">            <label>Password</label>            <input type="password" class="form-control"                name="Password" id="Password"                placeholder="Password" required>        </div>         <button type="submit"            class="btn btn-primary btn-lg">Login        </button>                 <button type="button"            class="btn btn-warning btn-lg"            id="register-button">            Create Account        </button>    </form>         <script>            $("#register-button").click(function () {                window.location.replace("register.php");            });    </script></body> </html>
PHP code of profile page: profile.php 
PHP
<!DOCTYPE html><html lang="en"><?php    session_start();?> <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Document</title>    <link rel="stylesheet" type="text/css"        href="css/style.css" media="screen" />     <!--  Adding bootstrap  -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"        crossorigin="anonymous">    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"        crossorigin="anonymous">    </script>         <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"        crossorigin="anonymous">    </script>         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"        crossorigin="anonymous">    </script>         <div class="nav-bar">        <div class="title">            <h3>welcome to my website</h3>        </div>    </div></head> <body>    <h1>welcome you are loggend in successfully</h1></body> </html>
Output:
ruhelaa48
adnanirshad158
anikakapoor
anikaseth98
gabaa406
surindertarika1234
simmytarika5
avtarkumar719
sagartomar9927
PHP-function
PHP-MySQL
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.