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. and set newid as a primary key while create table

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

CREATE TABLE `otpstore` (
`otp` varchar(10) NOT NULL,
`is_expired` int(11) NOT NULL,
`create_at` datetime NOT NULL,
`id` int(12) NOT NULL,
`newid` int(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

index.php


<?php
$success = "";
$error_message = "";
$conn = mysqli_connect("localhost","san-shopvfixu","San@123shop","san-shopvfix");
if(!empty($_POST["submit_email"])) {
    
    $_SESSION['email']=$_POST["email"];
$result = mysqli_query($conn,"SELECT * FROM user WHERE email='" . $_POST["email"] . "'");
$count  = mysqli_num_rows($result);
if($count>0) {
// generate OTP
$otp = rand(100000,999999);
// Send OTP
require_once("mail_function.php");
$mail_status = sendOTP($_POST["email"],$otp);
$mail_status=1; 
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;
}
.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($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) {
    $result = mysqli_query($conn,"SELECT * FROM otp_expiry WHERE otp='" . $_POST["otp"] . "'");

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

if($count > 0){

$_SESSION['newid']=$row['newid'];


}
header("Location: change-password.php");
        ?>
<?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>


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');
?>

11 comments

how to pay for OTP Login System through email address using php and Mysql.

Reply

Hello, can you please help me with this? I setup this script but and the OTP code gets sent but the script doesn't open the form for typing the OTP code.

Reply

I tried your code but it doesn't redirect to the the form where 'll type the OTP. Am I doing anything wrong?

Reply
Anonymous mod

Hi,
I follow all the steps but it's not working, i can receive OTP via email but the page keep asking to Enter Your Login Email in index.php page, anything not right?

Reply

Hi I followed ur steps on the codes but got some problem. I can receive otp via email but it keep asking me to enter email instead of otp. Secondly unable to register new user in MySQL , web said inserted success but MySQL no record updated.
Do you have any idea what went wrong ?

Reply

Sir,
email locates, it is OK
but when submit button is pressed

this page isn't working
unable to handle this request
HTTP ERROR 500

Reply

Hi Sorry for the delay. I recently updated the code and database table here pls check.

Reply

Hi Sorry for the delay. I recently updated the code and database table here pls check.

Reply

Hi Sorry for the delay. I missed new id in otpstore table. newid field shoud be primary key and i did some changes in the code. Now it is working fine. Please check

Reply

hi ,i tried your code but its shows me smtp error , can you plz help me

Reply

pls check your SMTP configuration details

Reply

Post a comment

Labels

360 degree view product image 3d rotate 3d text 3step-form Accordion menu ajax All Browsers Animated Background Gradient animation audio controller auto complete Best accordion menu bootstrap Bootstrap form validation border bounce effect on hover Breadcrumb calculate age by dob calendar Captcha change image on mouse move color chooser countdown Counter on scroll create random number Css css animation css buttons css hover css3 customized upload Button Date picker delete data from table Different scroll speed donation form download zip email otp verification email verifier Embed eventlist Expanding Menu feedbck form flash news section close button full screen menu Google custom search Google Maps Google reCAPTCHA Google site search gradient heart animation hide menu Horizontal News ticker Hover Htm Html html dropdown html form html form validation html5 html5 form validation Iframe image hover increment decrement textbox value based on select box Javascript javascript validation Jquery jquery validation js Layered image effect on mouse hover lock & unlock page scroll marquee marquee with close button mobile number validation mobile otp login Multi-level-drop-down-menu multi-level-form multi-select-checkbox Multi-Step-form Multiple File Upload in PHP mysql News ticker on hover change text to image our team page password generator password strength checker paypal form paypal html form Photoshop PHP php mailer populate html selectbox Popup image on click the link pure css Question type form random number generate Random password Redirect page Based on the select box while submit the form responsive responsive menu responsive popup box Responsive Vertical Time line design rotate image selectbox based on select box simple coming soon page simple countdown based on end date simple typing effect slider sliding tab sms otp login statistic counter on scroll switch tag shape team member Time picker toggle toggle view transparent button underline animation up down slide validation vertical fixed sidebar Webtips whatsapp link website Whislist Youtube