PHP Login with OTP Authentication over Email

PHP Login with OTP Authentication over Email – 15 Minutes OTP Validity Feature

Login with an OTP code is a protected strategy for the client verification process. In this strategy, a one-time secret word is created powerfully and sent to the client who endeavors to login. OTP can be sent to the client’s email or his cell phone. At the point when the client enters the OTP code then the application will confirm the client through this code.

In this model, when the enlisted client enters an email to login, an OTP code is sent to the email address. Utilizing this OTP code the client will be approved.

Login form with OTP

The following code shows a login form to the user to enter his email address. On entering email, it shows an input to enter the OTP code sent to his/Her email address. After submitting OTP, PHP will validate the code and show authentication result to the user.

Create Database Tables

The following SQL creates a otp_expiry & registered_users table with some basic fields in the MySQL database.

CREATE TABLE `otp_expiry` (
  `id` int(11) NOT NULL,
  `otp` varchar(10) NOT NULL,
  `is_expired` int(11) NOT NULL,
  `create_at` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `registered_users` (
  `id` int(11) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

PHP Code to Validate OTP Authentication

On presenting the email address, PHP content approves the client by checking the client database whether it is enrolled email. Provided that this is true, a 6 digit OTP code is created progressively by utilizing the PHP rand() work. You may decide to substitute this irregular code age rationale utilizing your favored component. This code is sent to the client’s email by utilizing PHPmailer.

PHP Login with OTP Authentication over Email

PHP Login with OTP ( Index.php )

<?php
 include "mail_function.php"; 
 date_default_timezone_set("Asia/Kolkata"); 
$success = "";
$error_message = "";
$conn = mysqli_connect("localhost","suneja","suneja","email_OTP");
if(!empty($_POST["submit_email"])) {
	$result = mysqli_query($conn,"SELECT * FROM registered_users WHERE email='" . $_POST["email"] . "'");
	$count  = mysqli_num_rows($result);
	if($count>0) {
		// generate OTP
		$otp = rand(100000,999999);
	
		// Send OTP
	   
		$mail_status = sendOTP($_POST["email"],$otp);
	
		if($mail_status == 1) {
		  
			$result = mysqli_query($conn,"INSERT INTO otp_expiry(otp,is_expired,create_at) VALUES ('" . $otp . "', 0, '" . date("Y-m-d H:i:s"). "')");
		
			$current_id = mysqli_insert_id($conn);
			
			
		
			
			if(!empty($current_id)) {
				$success=1;
			}
		}
	} else {
		$error_message = "Email not exists!";
	}
}
if(!empty($_POST["submit_otp"])) {
	$result = mysqli_query($conn,"SELECT * FROM otp_expiry WHERE otp='" . $_POST["otp"] . "' AND is_expired!=1 AND NOW() <= DATE_ADD(create_at, INTERVAL 24 HOUR)");
	$count  = mysqli_num_rows($result);
	if(!empty($count)) {
		$result = mysqli_query($conn,"UPDATE otp_expiry SET is_expired = 1 WHERE otp = '" . $_POST["otp"] . "'");
		$success = 2;	
	} else {
		$success =1;
		$error_message = "Invalid OTP!";
	}	
}
?>
<html>
<head>
<title>User Login</title>
<style>
body{
	font-family: calibri;
}
.tblLogin {
	border: #95bee6 1px solid;
    background: #d1e8ff;
    border-radius: 4px;
    max-width: 300px;
	padding:20px 30px 30px;
	text-align:center;
}
.tableheader { font-size: 20px; }
.tablerow { padding:20px; }
.error_message {
	color: #b12d2d;
    background: #ffb5b5;
    border: #c76969 1px solid;
}
.message {
	width: 100%;
    max-width: 300px;
    padding: 10px 30px;
    border-radius: 4px;
    margin-bottom: 5px;    
}
.login-input {
	border: #CCC 1px solid;
    padding: 10px 20px;
	border-radius:4px;
}
.btnSubmit {
	padding: 10px 20px;
    background: #2c7ac5;
    border: #d1e8ff 1px solid;
    color: #FFF;
	border-radius:4px;
}
</style>
</head>
<body>
	<?php
		if(!empty($error_message)) {
	?>
	<div class="message error_message"><?php echo $error_message; ?></div>
	<?php
		}
	?>

<form name="frmUser" method="post" action="">
	<div class="tblLogin">
		<?php 
			if(!empty($success == 1)) { 
		?>
		<div class="tableheader">Enter OTP</div>
		<p style="color:#31ab00;">Check your email for the OTP</p>
			
		<div class="tablerow">
			<input type="text" name="otp" placeholder="One Time Password" class="login-input" required>
		</div>
		<div class="tableheader"><input type="submit" name="submit_otp" value="Submit" class="btnSubmit"></div>
		<?php 
			} else if ($success == 2) {
        ?>
		<p style="color:#31ab00;">Welcome, You have successfully loggedin!</p>
		<?php
			}
			else {
		?>
		
		<div class="tableheader">Enter Your Login Email</div>
		<div class="tablerow"><input type="text" name="email" placeholder="Email" class="login-input" required></div>
		<div class="tableheader"><input type="submit" name="submit_email" value="Submit" class="btnSubmit"></div>
		<?php 
			}
		?>
	</div>
</form>
</body></html>

Implement OTP Verification

Now we will implement OTP verify on verify form submit. We will check for OTP if it is not expired and not more than 15 minutes then validate OTP otherwise display invalid OTP message to user to try login again. If OTP code is valid and verified then update it as expired after successful login authentication.

PHP Login with OTP ( mail_function.php )

<?php	
	function sendOTP($email,$otp) {
		require('phpmailer/class.phpmailer.php');
		require('phpmailer/class.smtp.php');
	
		$message_body = "One Time Password for PHP login authentication is:<br/><br/>" . $otp;
		$mail = new PHPMailer();
	   $mail->AddReplyTo('[email protected]','Technical Suneja');
                                $mail->SetFrom('[email protected]','Technical Suneja');
                                $mail->AddAddress($email);
                                $mail->Subject= "OTP to Login";
                                $mail->MsgHTML($message_body);
                                $result=$mail->Send();
                                if(!$result) {
                                    echo "Mailer Error: " . $mail->ErrorInfo;
                                }else {
                                    	return $result;  
                                } 
}
?>

These are the Main files and rest you can download from the below download button and if you have any concern regarding code then please put your comment down in the comment section.

Conclusion:-

The usefulness of this demo can be effectively upgraded according to your necessities and moreover you can integrate this demo in your website easily. When the enlisted client enters an email to login, an OTP code is sent to the email address. Utilizing this OTP code the client will be approved.

If you have any concerns regarding code then please put your comment down in the comment section.

For NEWS Updates – Click Here

3 Comments

  1. jay July 20, 2020
  2. Hammad July 22, 2020

Add Comment