Skip to main content

Build Login System with OTP using PHP & MySQL

Login with OTP (One Time Password) is a common functionality to make user login more secure. The One Time Password generated randomly and send to user email address or mobile to verify OTP code to complete login.

So if you’re thinking about implementing secure login with PHP using OTP, then you’re here at right place. In this tutorial, you will learn how to implement secure login in PHP with OTP code.

We will cover this tutorial in easy steps to implement secure login with OTP using PHP and MySQL. When login successful then OTP code send to email address and remain valid for one hour, after that code will be expired. The user login completed after OTP code verified. You can also create a complete User Management System with PHP & MySQL to manage everything related to users with admin panel.

Also, read:

So let’s start implementing secure login with OTP using PHP and MySQL. Before we begin, take a look on files structure for this example.

  • index.php
  • verify.php
  • welcome.php
  • logout.php

Step1: Create MySQL Database Table

As we will implement secure login with OTP with PHP and MySQL, so we will create MySQL database table members to store user login details.

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `username` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL,
  `password` varchar(250) NOT NULL,
  `authtoken` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

We will also create MySQL database table authentication to store login OTP details to validate OTP code.

CREATE TABLE `authentication` (
  `id` int(11) NOT NULL,
  `otp` varchar(10) NOT NULL,
  `expired` int(11) NOT NULL,
  `created` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Create Login Form

First in index.php, we will create user login form to implement login functionality.

<div class="col-md-6">                    
	<div class="panel panel-info" >
		<div class="panel-heading">
			<div class="panel-title">Sign In</div>                        
		</div> 
		<div style="padding-top:30px" class="panel-body" >
			<?php if ($errorMessage != '') { ?>
				<div id="login-alert" class="alert alert-danger col-sm-12"><?php echo $errorMessage; ?></div>                            
			<?php } ?>
			<form id="loginform" class="form-horizontal" role="form" method="POST" action="">                                    
				<div style="margin-bottom: 25px" class="input-group">
					<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
					<input type="text" class="form-control" id="email" name="email" placeholder="email">                                
				</div>                                
				<div style="margin-bottom: 25px" class="input-group">
					<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
					<input type="password" class="form-control" id="loginPass" name="loginPass" placeholder="password">
				</div>            
				<div style="margin-top:10px" class="form-group">                               
					<div class="col-sm-12 controls">
					  <input type="submit" name="login" value="Login" class="btn btn-success">						  
					</div>
				</div>                                
			</form>   
		</div>                     
	</div>  
</div>

Step3: Implement Login and Send OTP

We will implement user login functionality on login form submit. If user login successful, then send OTP code to user email address and insert OTP details to database table authentication. Also redirect to OTP code verify page for completing user login.

if(!empty($_POST["login"]) && $_POST["email"]!=''&& $_POST["loginPass"]!='') {	
	$email = $_POST['email'];
	$password = $_POST['loginPass'];
	$password = md5($password);
	$sqlQuery = "SELECT username FROM members WHERE email='".$email."' AND password='".$password."'";
	$resultSet = mysqli_query($conn, $sqlQuery) or die("database error:". mysqli_error($conn));
	$isValidLogin = mysqli_num_rows($resultSet);	
	if($isValidLogin){
		$userDetails = mysqli_fetch_assoc($resultSet);
		$_SESSION["user"] = $userDetails['username'];
		$otp = rand(100000, 999999);
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		$headers .= 'From: support@webdamn.com' . "\r\n";
		$messageBody = "One Time Password for login authentication is:

" . $otp; $messageBody = wordwrap($messageBody,70); $subject = "OTP to Login"; $mailStatus = mail($email, $subject, $messageBody, $headers); if($mailStatus == 1) { $insertQuery = "INSERT INTO authentication(otp, expired, created) VALUES ('".$otp."', 0, '".date("Y-m-d H:i:s")."')"; $result = mysqli_query($conn, $insertQuery); $insertID = mysqli_insert_id($conn); if(!empty($insertID)) { header("Location:verify.php"); } } } else { $errorMessage = "Invalid login!"; } } else if(!empty($_POST["email"])){ $errorMessage = "Enter Both user and password!"; }

Step4: Create Verify OTP Form

We will create OTP verify form in verify.php to very OTP for completing user login.

<div class="col-md-6">                    
	<div class="panel panel-info" >
		<div class="panel-heading">
			<div class="panel-title">Enter OTP</div>                        
		</div> 
		<div style="padding-top:30px" class="panel-body" >
			<?php if ($errorMessage != '') { ?>
				<div id="login-alert" class="alert alert-danger col-sm-12"><?php echo $errorMessage; ?></div>                            
			<?php } ?>
			<form id="authenticateform" class="form-horizontal" role="form" method="POST" action="">  					
				<div style="margin-bottom: 25px" class="input-group">
					<label class="text-success">Check your email for OTP</label>
					<input type="text" class="form-control" id="otp" name="otp" placeholder="One Time Password">                       
				</div>                          
				<div style="margin-top:10px" class="form-group">                               
					<div class="col-sm-12 controls">
					  <input type="submit" name="authenticate" value="Submit" class="btn btn-success">						  
					</div>
				</div>                                
			</form>   
		</div>                     
	</div>  
</div>

Step5: 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 one hour old 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.

if(!empty($_POST["authenticate"]) && $_POST["otp"]!='') {
	$sqlQuery = "SELECT * FROM authentication WHERE otp='". $_POST["otp"]."' AND expired!=1 AND NOW() <= DATE_ADD(created, INTERVAL 1 HOUR)";
	$result = mysqli_query($conn, $sqlQuery);
	$count = mysqli_num_rows($result);
	if(!empty($count)) {
		$sqlUpdate = "UPDATE authentication SET expired = 1 WHERE otp = '" . $_POST["otp"] . "'";
		$result = mysqli_query($conn, $sqlUpdate);
		header("Location:welcome.php");
	} else {
		$errorMessage = "Invalid OTP!";
	}	
} else if(!empty($_POST["otp"])){
	$errorMessage = "Enter OTP!";	
}	

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

7 thoughts on “Build Login System with OTP using PHP & MySQL

  1. after entering the otp successfully, we lose the user who wants to login! no connection between the otp and the member

  2. Thanks for that, handy to add a timezone to the session
    such as
    date_default_timezone_set(‘Europe/Amsterdam’);

    So that the sql now and inserted create value correspond

Comments are closed.