OTP Login System through email address using php and Mysql | Sanwebcorner

OTP Login System through email address using php and Mysql

Hi, Today i am going to post a article about Email otp concept. It will help you to login through the email otp. First OTP means one time password, It will randomly generated using php function, then it will store the database, when you login using opt then it will expired it valid only one time.

In this first you have to create database and tables, For that you just follow the below given sql query. Here is the two different table one is userprofile table to store the user emails and the second one is otpstore to store the randomly generated otp. First system checks the email is available in the database table. If not it shows the error email not exist. Just store some emails in database table and then try this program, then it will work perfectly and gives the otp to your registered email , After enter the OTP it takes the secure page.


The otp will send using the smtp through the phpmailer so you can provide the host name and email id, password, port number everyting in this mailfunction.php file. to deliver the otp email id. Using this concept you can set this for mobile otp concept. will post the Otp login via mobile in next post. I hope this example is very useful.





Database and Tables:

First create one database name called 'demo'

Use the below sql query to create table.

CREATE TABLE IF NOT EXISTS `userprofile` (
`id` int(11) NOT NULL,
  `email` varchar(255) NOT NULL
)

CREATE TABLE IF NOT EXISTS `otpstore` (
`id` int(11) NOT NULL,
  `otp` varchar(10) NOT NULL,
  `is_expired` int(11) NOT NULL,
  `create_at` datetime NOT NULL
)

index.php


<?php
$success = "";
$error_message = "";
$conn = mysqli_connect("localhost","root","","demo");
if(!empty($_POST["submit_email"])) {
$result = mysqli_query($conn,"SELECT * FROM userprofile WHERE email='" . $_POST["email"] . "'");
$count  = mysqli_num_rows($result);
if($count>0) {
// generate OTP
$otp = rand(1000,9999);
// Send OTP
require_once("mail_function.php");
$mail_status = sendOTP($_POST["email"],$otp);

if($mail_status == 1) {
$result = mysqli_query($conn,"INSERT INTO otpstore(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 otpstore 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 otpstore 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;
}
.form_container {
    border: 1px solid rgba(0, 0, 0, .05);
    box-shadow: 15px 26px 30px rgba(0, 0, 0, .09);
    border-left: 1px solid rgba(0, 0, 0, .06);
border-radius: 4px;
max-width: 500px;
padding: 20px 30px 30px;
text-align: center;
margin:0 auto;
}
.sanhead { font-size: 20px; }
.san { padding:20px; }
.error_message {
color: #b12d2d;
text-align: center;
background-color: #ffd9d9;
}
.message {
width: 100%;
max-width: 300px;
padding: 10px 30px;
border-radius: 4px;
margin: 0 auto;
margin-bottom: 5px;    
text-align: center;
}
.inputclass{
border: #CCC 1px solid;
padding: 10px 20px;
border-radius:4px;
}
.submit_button {
padding: 10px 20px;
background: #a9961e;
border: #736615 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="form_container">
<?php 
if($success == 1) { ?>
<div class="sanhead">Enter OTP</div>
<p style="color:#31ab00;">Check your email for the OTP</p>
<div class="san">
<input type="text" name="otp" placeholder="One Time Password" class="inputclass" required>
</div>
<div class="sanhead"><input type="submit" name="submit_otp" value="Submit" class="submit_button"></div>
<?php 
} else if ($success == 2) {
$result = mysqli_query($conn,"SELECT * FROM otpstore WHERE otp='" . $_POST["otp"] . "'");

$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result);

if($count > 0){
session_start();
$_SESSION['newid']=$row['newid'];
header('Location: securepage.php');
}
?>

<?php
}
else {
?>
<div class="sanhead">Enter Your Login Email</div>
<div class="san"><input type="text" name="email" placeholder="Email" class="inputclass" required></div>
<div class="sanhead"><input type="submit" name="submit_email" value="Submit" class="submit_button"></div>
<?php 
}
?>
</div>
</form>
</body>
</html>


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->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = 'tls'; // tls or ssl
$mail->Port     = "587";
$mail->Username = "your-mail-address";
$mail->Password = "password";
$mail->Host     = "your-host";
$mail->Mailer   = "smtp";
$mail->SetFrom("your-mail-address", "web");
$mail->AddAddress($email);
$mail->Subject = "OTP to Login";
$mail->MsgHTML($message_body);
$mail->IsHTML(true);
$result = $mail->Send();
return $result;
}
?>


securepage.php

<?php 
$conn = mysqli_connect("localhost","root","","demo");
ob_start(); session_start();
if(isset($_SESSION['newid']))
{
// header("location:index.php");
}
else
{
header("location:index.php");
}
?>
<div align="right"><a href="logout.php" style="margin-right:80px;">logout</a></div>
secure page test


logout.php

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