Thursday 25 June 2020

PHP Login Registration with Email Verification using OTP



Normally after user registration, we have send email at user register email address for confirm his or her email address. Once User has click on email confirmation link then after that user registration process has been completed with email verification.

But in this post, we have use OTP (One Time Password) method for verify registered user email address. Email verification is a very required process for check registered user has enter right information at the time of registration and it is also useful to prevent spam registration at our web application. For this reason verify user identity, we have to verify his or her email address. In this OTP method, If User has provide us genuine email address then on that email address our system will send one email confirmation email with OTP number. User has to just copy that OTP number and enter in email verification page which will be load after submitting registration form data. In that web page, User has to enter OTP number and submit form. After submitting form user email address will be verified.




In most of the dynamic website, there is user registration form. By fill up user registration form, user can register into web page. So in that registration form, If you have use OTP code for user email address verification, then it is the secure method for verify user email address. In this method, OTP Code will be generated at once user has submitted registration form details, and that OTP code will be received at registered user email address. So, when user has enters the OTP code then PHP web application will verify user email address via that OTP code.

In this tutorial, we will learn User registration process with email verification by using OTP method and here we will send OTP code using email. By using this OTP Code method user email address will be validated once user has enter OTP number which he or she received at their email address. Below you can find the source code of PHP registration system with email verification process using OTP method. In source code you can find how registration form has been made, then after we have first validated user registration form data by using PHP function. After form data verification, we have write PHP script to enter only unique user email data into Mysql database and then after send email with OTP number to registered user email address for email confirmation. After this you can find the source code of email verification by using OTP method.




How to Implement OTP based Login in PHP




In this PHP Registration with email verification using OTP method tutorial, here we have add one more feature like Login using OTP. In this section you can get the solution of Login into system using OTP. We all know OTP means one time password and this OTP number will be generated randomly by using PHP function and that randomly generated OTP number will be stored in Mysql database. So when you have login into system then that OTP number will be expired.

Now we have describe you, how to Login using OTP works. So, when you have login into system, then first you have to enter your login credentials like email address and password details. Then If you have enter right login information then at backend it will generated OTP number and that OTP number will be send to your registered email address. So you have to go to your email address inbox and copy that OTP number and enter into system. Once you have enter valid OTP number then system will validate and you can login into system and that OTP number has been expired. So, in this tutorial, we will OTP based Login system in PHP and below you can find the source code of it.

Make Default Avatar In PHP After User Registration





In this PHP Login Registration tutorial, we have add one more feature like create register user dynamic initial avatar once user has complete their registration process. This type of initial avatar or profile image we can see, when we have create account in Google, then after login into Google account then we can see our name first character image in place of profile image. So when we have register into Google system then it has by default create our initial avatar by using our name first character. We can change that avatar or profile image later by uploading image. So, this type of creating initial avatar from register user name feature we have made in this Login Registration tutorial by using PHP script.


PHP Resend Email Verification Mail with OTP Number




In this PHP Login Registration system, we have add one more feature like How can we resend email with OTP number for email verification process. For some reason, If User have completed their registration process but user has not received verification email with OTP number. Then at that time how user can verify their email address and again they cannot register into system, this is because user email address has been inserted in our system. So for overcome this problem, we have add this resend email verification email with OTP number by using PHP script. In this feature, User has to enter his or her register email which is not verified yet, then User has to enter that email address and User can again received email verification email with OTP Number.

PHP Forgot Password Recover using OTP Code


In this section of PHP Login Registration tutorial, we will learn How to reset forgot password by using OTP Code with PHP script. In this feature, User must have to register in our system, so if that user has forgot their password. Then by using this feature they can easily recover their forgot password. For make this feature, we have use PHP scipt, mysql database and PHPMailer class for send password reset OTP number to register email address.

In this feature, first Users has to enter their email address in forgot password form. Here user has to enter only that email which is register in system. If User enter register email address, then they will received one email address in which they can get OTP number. After submit form details then new web page has been load and in that page User has to enter OTP number which is received at their email address. After entering OTP number then after again new form has been load on web page, and here User has to reset new password and submit form. After submitting form User password will be reset and they can again login into system. So, in this section we have make PHP forgot password script using OTP method.




Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `login_data`
--

CREATE TABLE `login_data` (
  `login_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `login_otp` int(6) NOT NULL,
  `last_activity` datetime NOT NULL,
  `login_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `register_user`
--

CREATE TABLE `register_user` (
  `register_user_id` int(11) NOT NULL,
  `user_name` varchar(250) NOT NULL,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL,
  `user_activation_code` varchar(250) NOT NULL,
  `user_email_status` enum('not verified','verified') NOT NULL,
  `user_otp` int(11) NOT NULL,
  `user_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `user_avatar` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `login_data`
--
ALTER TABLE `login_data`
  ADD PRIMARY KEY (`login_id`);

--
-- Indexes for table `register_user`
--
ALTER TABLE `register_user`
  ADD PRIMARY KEY (`register_user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `login_data`
--
ALTER TABLE `login_data`
  MODIFY `login_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;

--
-- AUTO_INCREMENT for table `register_user`
--
ALTER TABLE `register_user`
  MODIFY `register_user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;





index.php



<?php

//index.php

//error_reporting(E_ALL);

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

include('function.php');

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

$message = '';
$error_user_name = '';
$error_user_email = '';
$error_user_password = '';
$user_name = '';
$user_email = '';
$user_password = '';

if(isset($_POST["register"]))
{
 if(empty($_POST["user_name"]))
 {
  $error_user_name = "<label class='text-danger'>Enter Name</label>";
 }
 else
 {
  $user_name = trim($_POST["user_name"]);
  $user_name = htmlentities($user_name);
 }

 if(empty($_POST["user_email"]))
 {
  $error_user_email = '<label class="text-danger">Enter Email Address</label>';
 }
 else
 {
  $user_email = trim($_POST["user_email"]);
  if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
  {
   $error_user_email = '<label class="text-danger">Enter Valid Email Address</label>';
  }
 }

 if(empty($_POST["user_password"]))
 {
  $error_user_password = '<label class="text-danger">Enter Password</label>';
 }
 else
 {
  $user_password = trim($_POST["user_password"]);
  $user_password = password_hash($user_password, PASSWORD_DEFAULT);
 }

 if($error_user_name == '' && $error_user_email == '' && $error_user_password == '')
 {
  $user_activation_code = md5(rand());

  $user_otp = rand(100000, 999999);

  $data = array(
   ':user_name'  => $user_name,
   ':user_email'  => $user_email,
   ':user_password' => $user_password,
   ':user_activation_code' => $user_activation_code,
   ':user_email_status'=> 'not verified',
   ':user_otp'   => $user_otp
  );

  $query = "
  INSERT INTO register_user 
  (user_name, user_email, user_password, user_activation_code, user_email_status, user_otp)
  SELECT * FROM (SELECT :user_name, :user_email, :user_password, :user_activation_code, :user_email_status, :user_otp) AS tmp
  WHERE NOT EXISTS (
      SELECT user_email FROM register_user WHERE user_email = :user_email
  ) LIMIT 1
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($connect->lastInsertId() == 0)
  {
   $message = '<label class="text-danger">Email Already Register</label>';
  } 
  else
  {
   $user_avatar = make_avatar(strtoupper($user_name[0]));

   $query = "
   UPDATE register_user 
   SET user_avatar = '".$user_avatar."' 
   WHERE register_user_id = '".$connect->lastInsertId()."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();


   require 'class/class.phpmailer.php';
   $mail = new PHPMailer;
   $mail->IsSMTP();
   $mail->Host = 'smtpout.secureserver.net';
   $mail->Port = '80';
   $mail->SMTPAuth = true;
   $mail->Username = 'xxxxxxxxxxxxxx';
   $mail->Password = 'xxxxxxxxxxxxxx';
   $mail->SMTPSecure = '';
   $mail->From = 'tutorial@webslesson.info';
   $mail->FromName = 'Webslesson';
   $mail->AddAddress($user_email);
   $mail->WordWrap = 50;
   $mail->IsHTML(true);
   $mail->Subject = 'Verification code for Verify Your Email Address';

   $message_body = '
   <p>For verify your email address, enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
   <p>Sincerely,</p>
   <p>Webslesson.info</p>
   ';
   $mail->Body = $message_body;

   if($mail->Send())
   {
    echo '<script>alert("Please Check Your Email for Verification Code")</script>';

    header('location:email_verify.php?code='.$user_activation_code);
   }
   else
   {
    $message = $mail->ErrorInfo;
   }
  }

 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Registration with Email Verification using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Registration with Email Verification using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Registration</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Name</label>
       <input type="text" name="user_name" class="form-control" />
       <?php echo $error_user_name; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
       <?php echo $error_user_email; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Password</label>
       <input type="password" name="user_password" class="form-control" />
       <?php echo $error_user_password; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-success" value="Click to Register" />&nbsp;&nbsp;&nbsp;
       <a href="resend_email_otp.php" class="btn btn-default">Resend OTP</a>
       &nbsp;&nbsp;&nbsp;
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


email_verify.php



<?php

//email_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$error_user_otp = '';
$user_activation_code = '';
$message = '';

if(isset($_GET["code"]))
{
 $user_activation_code = $_GET["code"];

 if(isset($_POST["submit"]))
 {
  if(empty($_POST["user_otp"]))
  {
   $error_user_otp = 'Enter OTP Number';
  }
  else
  {
   $query = "
   SELECT * FROM register_user 
   WHERE user_activation_code = '".$user_activation_code."' 
   AND user_otp = '".trim($_POST["user_otp"])."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();

   $total_row = $statement->rowCount();

   if($total_row > 0)
   {
    $query = "
    UPDATE register_user 
    SET user_email_status = 'verified' 
    WHERE user_activation_code = '".$user_activation_code."'
    ";

    $statement = $connect->prepare($query);

    if($statement->execute())
    {
     header('location:login.php?register=success');
    }
   }
   else
   {
    $message = '<label class="text-danger">Invalid OTP Number</label>';
   }
  }
 }
}
else
{
 $message = '<label class="text-danger">Invalid Url</label>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Registration with Email Verification using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Registration with Email Verification using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Enter OTP Number</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
       <?php echo $error_user_otp; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Submit" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>



login.php



<?php

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">How to Make Initial Avatar Image in PHP After Registration</h3>
   <br />

   <?php
   if(isset($_GET["register"]))
   {
    if($_GET["register"] == 'success')
    {
     echo '
     <h1 class="text-success">Email Successfully verified, Registration Process Completed...</h1>
     ';
    }
   }

   if(isset($_GET["reset_password"]))
   {
    if($_GET["reset_password"] == 'success')
    {
     echo '<h1 class="text-success">Password change Successfully, Now you can login with your new password</h1>';
    }
   }
   ?>

   <div class="row">
    <div class="col-md-3">&nbsp;</div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Login</h3>
      </div>
      <div class="panel-body">
       <form method="POST" id="login_form">
        <div class="form-group" id="email_area">
         <label>Enter Email Address</label>
         <input type="text" name="user_email" id="user_email" class="form-control" />
         <span id="user_email_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="password_area" style="display:none;">
         <label>Enter password</label>
         <input type="password" name="user_password" id="user_password" class="form-control" />
         <span id="user_password_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="otp_area" style="display:none;">
         <label>Enter OTP Number</label>
         <input type="text" name="user_otp" id="user_otp" class="form-control" />
         <span id="user_otp_error" class="text-danger"></span>
        </div>
        <div class="form-group" align="right">
         <input type="hidden" name="action" id="action" value="email" />
         <input type="submit" name="next" id="next" class="btn btn-primary" value="Next" />
        </div>
       </form>
      </div>
     </div>
     <div align="center">
      <b><a href="forget_password.php?step1=1">Forgot Password</a></b>
     </div>
    </div>
   </div>
   
  </div>
  <br />
  <br />
 </body>
</html>

<script>

$(document).ready(function(){
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  var action = $('#action').val();
  $.ajax({
   url:"login_verify.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#next').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#next').attr('disabled', false);
    if(action == 'email')
    {
     if(data.error != '')
     {
      $('#user_email_error').text(data.error);
     }
     else
     {
      $('#user_email_error').text('');
      $('#email_area').css('display', 'none');
      $('#password_area').css('display', 'block');
     }
    }
    else if(action == 'password')
    {
     if(data.error != '')
     {
      $('#user_password_error').text(data.error);
     }
     else
     {
      $('#user_password_error').text('');
      $('#password_area').css('display', 'none');
      $('#otp_area').css('display', 'block');
     }
    }
    else
    {
     if(data.error != '')
     {
      $('#user_otp_error').text(data.error);
     }
     else
     {
      window.location.replace("home.php");
     }
    }

    $('#action').val(data.next_action);
   }
  })
 });
});

</script>








login_verify.php



<?php

//login_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

session_start();

$error = '';

$next_action = '';

sleep(2);

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'email')
 {
  if($_POST["user_email"] != '')
  {
   $data = array(
    ':user_email' => $_POST["user_email"]
   );

   $query = "
   SELECT * FROM register_user 
   WHERE user_email = :user_email
   ";

   $statement = $connect->prepare($query);

   $statement->execute($data);

   $total_row = $statement->rowCount();

   if($total_row == 0)
   {
    $error = 'Email Address not found';

    $next_action = 'email';
   }
   else
   {
    $result = $statement->fetchAll();

    foreach($result as $row)
    {
     $_SESSION["register_user_id"] = $row["register_user_id"];

     $_SESSION["user_name"] = $row["user_name"];

     $_SESSION['user_email'] = $row["user_email"];

     $_SESSION["user_password"] = $row["user_password"];
    }
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Email Address is Required';

   $next_action = 'email';
  }
 }

 if($_POST["action"] == 'password')
 {
  if($_POST["user_password"] != '')
  {
   if(password_verify($_POST["user_password"], $_SESSION["user_password"]))
   {
    $login_otp = rand(100000,999999);

    $data = array(
     ':user_id'  => $_SESSION["register_user_id"],
     ':login_otp' => $login_otp,
     ':last_activity'=> date('d-m-y h:i:s')
    );

    $query = "
    INSERT INTO login_data 
    (user_id, login_otp, last_activity) 
    VALUES (:user_id, :login_otp, :last_activity)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $_SESSION['login_id'] = $connect->lastInsertId();
     $_SESSION['login_otp'] = $login_otp;

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'xxxxxxxxxxxxxx';
     $mail->Password = 'xxxxxxxxxxxxxx';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($_SESSION["user_email"]);

     $mail->WordWrap = 50;

     $mail->IsHTML(true);

     $mail->Subject = 'Verification code for Login';

     $message_body = '
     <p>For verify your login details, enter this verification code when prompted: <b>'.$login_otp.'</b>.</p>
     <p>Sincerely,</p>
     <p>Webslesson.info</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      $next_action = 'otp';
     }
     else
     {
      $error = '<label class="text-danger">'.$mail->ErrorInfo.'</label>';
      $next_action = 'password';
     }
    }
   }
   else
   {
    $error = 'Wrong Password';
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Password is Required';
   $next_action = 'password';
  }
 }

 if($_POST["action"] == "otp")
 {
  if($_POST["user_otp"] != '')
  {
   if($_SESSION['login_otp'] == $_POST["user_otp"])
   {
    $_SESSION['user_id'] = $_SESSION['register_user_id'];
    unset($_SESSION["register_user_id"]);
    unset($_SESSION["user_email"]);
    unset($_SESSION["user_password"]);
    unset($_SESSION["login_otp"]);
   }
   else
   {
    $error = 'Wrong OTP Number';
    $next_action = 'otp';
   }
  }
  else
  {
   $error = 'OTP Number is required';
   $next_action = 'otp';
  }
 }





 $output = array(
  'error'   => $error,
  'next_action' => $next_action
 );

 echo json_encode($output);
}


?>


home.php



<?php

//home.php

session_start();

if(!isset($_SESSION["user_id"]))
{
 header("location:login.php");
}

include('database_connection.php');

include('function.php');

$user_name = '';
$user_id = '';

if(isset($_SESSION["user_name"], $_SESSION["user_id"]))
{
 $user_name = $_SESSION["user_name"];
 $user_id = $_SESSION["user_id"];
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">How to Make Initial Avatar Image in PHP After Registration</h3>
   <br />
   <br />
   <div class="row">
    <div class="col-md-9">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">User Timeline</h3>
      </div>
      <div class="panel-body">
       <h1 align="center">Welcome <?php echo $user_name; ?></h1>
      </div>
     </div>
    </div>
    <div class="col-md-3">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">User Details</h3>
      </div>
      <div class="panel-body">
       <div align="center">
        <?php
        Get_user_avatar($user_id, $connect);
        echo '<br /><br />';
        echo $user_name;
        ?>
        <br />
        <br />
        <a href="logout.php" class="btn btn-default">Logout</a>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


logout.php



<?php

//logout.php

session_start();

session_destroy();

header("location:login.php");

?>


resend_email_otp.php



<?php

//resend_email_otp.php

include('database_connection.php');

$message = '';

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

if(isset($_POST["resend"]))
{
 if(empty($_POST["user_email"]))
 {
  $message = '<div class="alert alert-danger">Email Address is required</div>';
 }
 else
 {
  $data = array(
   ':user_email' => trim($_POST["user_email"])
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_email = :user_email
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if($row["user_email_status"] == 'verified')
    {
     $message = '<div class="alert alert-info">Email Address already verified, you can login into system</div>';
    }
    else
    {
     require 'class/class.phpmailer.php';
     $mail = new PHPMailer;
     $mail->IsSMTP();
     $mail->Host = 'smtpout.secureserver.net';
     $mail->Port = '80';
     $mail->SMTPAuth = true;
     $mail->Username = 'xxxxxxxxx';
     $mail->Password = 'xxxxxxxxx';
     $mail->SMTPSecure = '';
     $mail->From = 'tutorial@webslesson.info';
     $mail->FromName = 'Webslesson';
     $mail->AddAddress($row["user_email"]);
     $mail->WordWrap = 50;
     $mail->IsHTML(true);
     $mail->Subject = 'Verification code for Verify Your Email Address';
     $message_body = '
     <p>For verify your email address, enter this verification code when prompted: <b>'.$row["user_otp"].'</b>.</p>
     <p>Sincerely,</p>
     ';
     $mail->Body = $message_body;

     if($mail->Send())
     {
      echo '<script>alert("Please Check Your Email for Verification Code")</script>';
      echo '<script>window.location.replace("email_verify.php?code='.$row["user_activation_code"].'");</script>';
     }
     else
     {

     }
    }
   }
  }
  else
  {
   $message = '<div class="alert alert-danger">Email Address not found in our record</div>';
  }
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Resend Email Verification OTP in PHP Registration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Resend Email Verification OTP in PHP Registration</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Resend Email Verification OTP</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="email" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="resend" class="btn btn-success" value="Send" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>





forget_password.php



<?php

//forget_password.php

include('database_connection.php');

$message = '';

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

if(isset($_POST["submit"]))
{
 if(empty($_POST["user_email"]))
 {
  $message = '<div class="alert alert-danger">Email Address is required</div>';
 }
 else
 {
  $data = array(
   ':user_email' => trim($_POST["user_email"])
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_email = :user_email
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   $result = $statement->fetchAll();

   foreach($result as $row)
   {
    if($row["user_email_status"] == 'not verified')
    {
     $message = '<div class="alert alert-info">Your Email Address is not verify, so first verify your email address by click on this <a href="resend_email_otp.php">link</a></div>';
    }
    else
    {
     $user_otp = rand(100000, 999999);

     $sub_query = "
     UPDATE register_user 
     SET user_otp = '".$user_otp."' 
     WHERE register_user_id = '".$row["register_user_id"]."'
     ";

     $connect->query($sub_query);

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'xxxxxxxxxxxx';

     $mail->Password = 'xxxxxxxxxxx';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($row["user_email"]);

     $mail->IsHTML(true);

     $mail->Subject = 'Password reset request for your account';

     $message_body = '
     <p>For reset your password, you have to enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
     <p>Sincerely,</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      echo '<script>alert("Please Check Your Email for password reset code")</script>';

      echo '<script>window.location.replace("forget_password.php?step2=1&code=' . $row["user_activation_code"] . '")</script>';
     }
    }
   }
  }
  else
  {
   $message = '<div class="alert alert-danger">Email Address not found in our record</div>';
  }
 }
}

if(isset($_POST["check_otp"]))
{
 if(empty($_POST["user_otp"]))
 {
  $message = '<div class="alert alert-danger">Enter OTP Number</div>';
 }
 else
 {
  $data = array(
   ':user_activation_code'  => $_POST["user_code"],
   ':user_otp'     => $_POST["user_otp"]
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_activation_code = :user_activation_code 
  AND user_otp = :user_otp
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   echo '<script>window.location.replace("forget_password.php?step3=1&code=' . $_POST["user_code"] . '")</script>';
  }
  else
  {
   $message = '<div class="alert alert-danger">Wrong OTP Number</div>';
  }
 }
}

if(isset($_POST["change_password"]))
{
 $new_password = $_POST["user_password"];
 $confirm_password = $_POST["confirm_password"];

 if($new_password == $confirm_password)
 {
  $query = "
  UPDATE register_user 
  SET user_password = '".password_hash($new_password, PASSWORD_DEFAULT)."' 
  WHERE user_activation_code = '".$_POST["user_code"]."'
  ";

  $connect->query($query);

  echo '<script>window.location.replace("login.php?reset_password=success")</script>';
 }
 else
 {
  $message = '<div class="alert alert-danger">Confirm Password is not match</div>';
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Forgot Password script in PHP using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Forgot Password script in PHP using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Forgot Password script in PHP using OTP</h3>
    </div>
    <div class="panel-body">
     <?php

     echo $message;

     if(isset($_GET["step1"]))
     {
     ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Send" />
      </div>
     </form>
     <?php
     }
     if(isset($_GET["step2"], $_GET["code"]))
     {
     ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
      </div>
      <div class="form-group">
       <input type="hidden" name="user_code" value="<?php echo $_GET["code"]; ?>" />
       <input type="submit" name="check_otp" class="btn btn-success" value="Send" />
      </div>
     </form>
     <?php
     }

     if(isset($_GET["step3"], $_GET["code"]))
     {
     ?>
     <form method="post">
      <div class="form-group">
       <label>Enter New Password</label>
       <input type="password" name="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Confirm Password</label>
       <input type="password" name="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="hidden" name="user_code" value="<?php echo $_GET["code"]; ?>" />
       <input type="submit" name="change_password" class="btn btn-success" value="Change" />
      </div>
     </form>
     <?php 
     }
     ?>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


function.php



<?php

//function.php

function make_avatar($character)
{
    $path = "avatar/". time() . ".png";
 $image = imagecreate(200, 200);
 $red = rand(0, 255);
 $green = rand(0, 255);
 $blue = rand(0, 255);
    imagecolorallocate($image, $red, $green, $blue);  
    $textcolor = imagecolorallocate($image, 255,255,255);  

    imagettftext($image, 100, 0, 55, 150, $textcolor, 'font/arial.ttf', $character);  
    //header("Content-type: image/png");  
    imagepng($image, $path);
    imagedestroy($image);
    return $path;
}

function Get_user_avatar($user_id, $connect)
{
 $query = "
 SELECT user_avatar FROM register_user 
    WHERE register_user_id = '".$user_id."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 foreach($result as $row)
 {
  echo '<img src="'.$row["user_avatar"].'" width="75" class="img-thumbnail img-circle" />';
 }
}

?>





59 comments:

  1. Thank you for this best tutorial.
    Could you do a PDO tutorial for different profiles ie when a person x connects what he receives is entirely different from another person y ? thank you in advance

    ReplyDelete
  2. Thank you for this best tutorial.
    Could you do a PDO tutorial for different profiles ie when a person x connects what he receives is entirely different from another person y? thank you in advance

    ReplyDelete
  3. Nice Information Sir. Very Helpful

    ReplyDelete
  4. please for mobile number otp i want

    ReplyDelete
  5. I keep getting 'email already registered'!

    ReplyDelete
    Replies
    1. Same here! Solution please

      Delete

    2. Hi, If you have face email already register error that means, your email address has been already register in this system, so now you can visit http://demo.webslesson.info/otp-php-registration/resend_email_otp.php this link and resend OTP message by entering email address in which you have face email already register error, so you can confirm your email address, and you can login into system.

      After visiting this link and you have not received email confirming OTP number, then please share your email address, so we will check in our system.

      Delete
    3. did you guys found the solution to this??? having the same error here.
      help please.

      Delete
    4. even me same problem email already register error

      Delete
  6. Where are the registration page

    ReplyDelete
  7. "Email already register" how can I fix it?
    Please help

    ReplyDelete
    Replies
    1. Hi, If you have face email already register error that means, your email address has been already register in this system, so now you can visit http://demo.webslesson.info/otp-php-registration/resend_email_otp.php this link and resend OTP message by entering email address in which you have face email already register error, so you can confirm your email address, and you can login into system.

      After visiting this link and you have not received email confirming OTP number, then please share your email address, so we will check in our system.

      Delete
    2. I have no data inside the both the table, when i try to register it throws error,"Email Already Register"

      Delete
    3. Hey i downloaded the source code and try to run it in my own host, and its saying the same "Email already registered help please, what could be the reason since no any data in my table." PLEASE HELP as i am stuck.
      Thank you:)

      Delete
    4. Você tem que ativar uma função no seu email de aceitar receber email de aplicação desconhecida, depois testa que é sucesso.

      Delete
  8. In login after password input OTP area not showing(Received login otp).

    ReplyDelete
    Replies
    1. Hello dealzones how did you fix "email already registered" issue???

      Delete
    2. I didn't got that issue...

      Delete
  9. Hello bro how can I fix smtp connect()failed

    ReplyDelete
    Replies
    1. Ask you hosting company the SMTP details, had the same error but the below code solved it, in file index.php and other files which needs it, you should change.
      $mail->Host = 'smtp.hostinger.com';// instead of smtpout.secureserver.net which is his host, replace with yours.
      $mail->Port = '587'; //replace with yours too
      $mail->SMTPAuth = true;
      $mail->Username = 'YOUR HOST USERNAME';
      $mail->Password = 'your password here';
      $mail->SMTPSecure = 'SSL'; //just put SSL
      $mail->From = 'YOUE EMAIL';

      THAT SHOULD HELP

      Delete
  10. thank u for those codes, btw im getting problem after i tried insert my login email, i can't click the login button suddenly. im stucked. can u help me why?

    ReplyDelete
  11. i got email already register error can u say the solution

    ReplyDelete
  12. hi friend as you have connected a database_connection.php in the Forgotten password so where i can get that php file

    ReplyDelete
  13. Good job. Please the zip files is corrupt, source code cannot be download.PHPMAILER and connection is not found in above code

    ReplyDelete
  14. I am not enable to download source code.

    ReplyDelete
  15. your demo page in not working

    ReplyDelete
  16. Same problem user already exist and my table are empty

    ReplyDelete
  17. I spent too much time to create tables and after all not working user already exist, not working at all even resend or login, sorry....

    ReplyDelete
  18. Even I tried new user with new email the same error,,,,,

    ReplyDelete
  19. javascript: resendRegistrationCode();

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Dear sir,
    why unverifie user can log in?
    in your demo unverifie user can not log in.
    but in source code this option is not working.

    ReplyDelete
  22. class 'SMTP' not found

    PLEASE HELP!

    ReplyDelete
  23. Fatal error: Uncaught Error: Class 'PHPMailer' not found in C:\xampp\htdocs\OTP1\index.php:110 Stack trace: #0 {main} thrown in C:\xampp\htdocs\OTP1\index.php on line 110

    how to solve

    ReplyDelete
  24. SMTP Connect() failed. and
    Warning: imagettftext(): Invalid font filename in C:\xampp\htdocs\nnewotp\function.php on line 15 while running in localhost indly help how to configure in local and hosting.

    ReplyDelete

  25. Warning: imagettftext(): Invalid font filename in C:\xampp\htdocs\weblesson\function.php on line 15

    Warning: imagepng(avatar/1613129892.png): failed to open stream: No such file or directory in C:\xampp\htdocs\weblesson\function.php on line 17

    Fatal error: Uncaught Error: Class 'PHPMailer' not found in C:\xampp\htdocs\weblesson\index.php:109 Stack trace: #0 {main} thrown in C:\xampp\htdocs\weblesson\index.php on line 109

    ReplyDelete
  26. Can you post the source code for class/class.phpmailer.php, since this is needed for the OTP register

    ReplyDelete
  27. I have the same problem while the database is still empty.

    ReplyDelete
  28. thank you so much for this.. it helped me a lot. Pls, have set the whole code up, but during registration, it tells me the email is already taken, while the email is not in the database record, infant my database is empty. Pls what can I do. I could have sent a screen shot, if I'm chanced

    ReplyDelete
  29. smtp connect() failed
    .please give me solution.

    ReplyDelete
  30. how can i use the source and how can i change values to connect smtp with my localhost and my gmail account to send and verification email to my gmail account to verify users account on the platform

    ReplyDelete
  31. i have to change just the username and password after "$mail->SMTPAuth = true;" to make smtp connecting to my email adress

    ReplyDelete
  32. sir, How to fix SMTP connect() failed error please reply me sir.....

    ReplyDelete
    Replies
    1. configure it po , use smtp.gmail.com and use your gmail account as sender

      Delete
  33. SMTP Connect() failed. I need a help please

    ReplyDelete
    Replies
    1. use ur gmail acct. instead, and use this smtp.gmail.com

      Delete
  34. Fatal error: Uncaught Error: Call to undefined function imagecreatetruecolor() in C:\xampp\htdocs\ls\function.php:8 Stack trace: #0 C:\xampp\htdocs\ls\index.php(95): make_avatar('L') #1 {main} thrown in C:\xampp\htdocs\ls\function.php on line 8
    pls help me gettin error like this

    ReplyDelete
  35. Where is database_connect.php??

    ReplyDelete
  36. Fatal error: Uncaught Error: Call to undefined function imagecreate() in C:\xampp\htdocs\otp-php-registration\function.php:8 Stack trace: #0 C:\xampp\htdocs\otp-php-registration\index.php(95): make_avatar('R') #1 {main} thrown in C:\xampp\htdocs\otp-php-registration\function.php on line 8

    ReplyDelete
  37. i cant see database_connection.php file

    ReplyDelete
  38. forget password does not work. Input does not appear

    ReplyDelete
  39. Hi i have a question
    can u guide me ?

    ReplyDelete