Skip to main content

Email OTP

email otp sms

Email OTP

Login with an OTP code is a secure method for the user authentication process. In this method, a one-time password is generated dynamically and sent to the user who attempts login. OTP can be sent to the user’s email or his mobile phone. When the user enters the OTP code then the application will authenticate the user via this code.
In this tutorial, we are going to see an example to authenticate user login via an OTP code using email. You can check our mobile sms otp too!
 In this example, when the registered user enters email to login, an OTP code is sent to the email address. Using this OTP code the user will be validated. Once the user uses this code then it will be invalid, meaning it cannot be used again. Also, this token will be valid for a day, then it will be expired.

Login form with OTP

The following code shows 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 email address. After submitting OTP, PHP will validate the code and show authentication result to the user.

<?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>
On submitting the email address, PHP script validates the user by checking the user database whether it is registered email. If so, a 6 digit OTP code is generated dynamically by using the PHP rand() function. You may choose to substitute this random code generation logic using your preferred mechanism. This code is sent to the user’s email by using PHPmailer. When the user submits the OTP code to PHP, it validates the code by checking its expiration. The code is valid for one day and it will be expired once it is used. The PHP code is,



<?php $success = "";
$error_message = "";
$conn = mysqli_connect("localhost","root","","blog_samples");
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 require_once("mail_function.php"); $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!"; } } ?>

Comments

Popular posts from this blog

how to create Session cookies in php

What are Session cookies Session cookies , also known as ' temporary cookies ', help websites recognise users and the information provided when they navigate through a website. Session cookies only retain information about a user's activities for as long as they are on the website. Once the web browser is closed, the cookies are deleted. These are commonly used on shopping websites or e-commerce websites.We have already talked about cookies, Learn all about cookies . Cookies are the reason Trednix.com remembers your username between visits and the reason you don’t necessarily need to log in to your Hotmail account every time you open your browser. Cookie data typically contains a short set of information regarding when you last accessed a site, an ID number, and, potentially, information about your visit. Let’s now look at the basic syntax used to create a cookie. <?php setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponl...

How to create a search engine

How to create a search engine I am going to teach you how we can create a search engine using Google API . You can add more styles to it ,because I'd be creating a simple looking search engine. Google Custom Search API are wonderful tools to create some awesome search engine like tools. Also if you want to add a search option to your website and customize the look and feel of your search results, Google Custom Search API serve best to you. I have created a Real Time Search engine (I call it real time as it search as you type). I am really impressed by the speed/response of Google Search API. In order to use Google Search API, you have to first generate a Key for you. Go to following page and signup your self for the Key. Sign up for Google API Key https://code.google.com/apis/ajaxsearch/signup.html Next step is to include the Google Search API javascript. Don’t forget to mention your key in the below code. <script src="http://www.google.com/jsapi?key=YOURKEY...

All you need to know about web cookies

Hello guys ,we all know as a web developers we need cookies ,i am not talking about the normal cookies , I'm talking of web cookies , it's a really good cookie for us 😋.All dynamic website uses cookies in one way or the other and we would be talking about all the types of cookies websites uses. What are cookies? Cookies are small text files placed on a user’s computer (or smartphone), which are commonly used to collect personal data. Most website operators place cookies on the browser or hard drive of their user's computer. Cookies can gather information about the use of a website or enable the website to recognise the user as an existing customer when they return to the website at a later date. This file is neither a virus nor spyware. The law protects website users and lets them opt-out from the use of cookies on their website browser. What are the benefits of cookies? Cookies are used to make the user's web experience faster, convenient and personalised. ...