Dj Techblog

A blog on web development

Email otp verification in php

Last Modified on October 11, 2021
Email verification in php using OTP

Email verification via OTP is most widely used technique to verify the Email address of a client or an user during registration process. It is used in variety of websites or applications.

For OTP verification, we use php rand() function to generate OTP and send it to email id via php mail() function. On receiving the OTP user enters the otp in a verification form, which is sent again to server. If otp entered by the user matches with the otp stored in session, email is verified.

Why do we need email verification using OTP?

The whole purpose of email verification is to ensure that only real users with a valid email address will interact with the online system. This helps the admin to restrict spamming.

For Email verification using OTP create these files in your server.

  1. Landing page: index.php

  2. script.js

  3. controller.php

  4. otp-verification.php

  5. style.css

Get Email id to send OTP

User enters his email id to receive otp. If non valid email is provided by the user, it returns an error.

Landing page : index.php

<!DOCTYPE html>
<html>
<head>
<title>Email verification form in php using otp</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>
<body>

	<div class="container w3-card">
		<div class="err"></div>
		<form id="mobile-number-verification">
			<div class="mobile-heading">Email Verification</div>
			<div class="mobile-row">
				<input type="text" id="name" class="mobile-input" placeholder="Enter your name">
				<br>
				<div id="message1"></div>
				<br>
				<input type="email" id="email" class="mobile-input" placeholder="Enter your email-id">
				<div id="message2"></div>
			</div>
			<div id="loading-image"><img src="/image/ajax-loader.gif" alt="ajax loader"></div>
			<input type="button" class="mobileSubmit" id="enter" disabled="true" value="Get OTP" onClick="getOTP();">
		</form>
		<script>
		    $('#email').on('keyup',function(){
  		            var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  		            var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  		            var email = $("#email").val();
  		            if(email.match(mailformat)){
  		                $('#message2').html('valid').css('color','green');
  		                $("#enter").prop('disabled',false);
  		            }
  		            else
  		                $('#message2').html('Invalid Email').css('color','red');
  		                
  		        }
  		        );
		</script>
	</div>
	</body>
</html>

email verification in php using otp

Makes an ajax request to server for otp generation

When the user clicks on the Login button, a javascript function is called. The function does some checking at the client-side and makes an ajax request to the server to generate otp.

script.js

function getOTP() {
	$(".err").html("").hide();
	var email = $("#email").val();
	var name = $("#name").val();	
	if(name.length !== 0)
	{
	    var input ={
	        "name" : name,
	        "email" : email,
	        "action" : "get_otp"
	    }
	    $("#loading-image").show();
	    $.ajax({
	        
	        url : 'controller.php',
	        type : 'POST',
	        data : input,
	        success : function(response)
	        {
	            $(".container").html(response);
	        },
	        complete : function()
	        {
	            $("#loading-image").hide();
	        }
	        
	    });
	}
	else
	    $("#message1").html("Enter your name").css('color','red');
	
}

function verifyOTP() {
	$(".err").html("").hide();
	$(".success").html("").hide();
	var otp = $("#mobileOtp").val();
	var input = {
		"otp" : otp,
		"action" : "verify_otp"
	};
	if (otp.length == 6 && otp != null) {
		$.ajax({
			url : 'controller.php',
			type : 'POST',
			dataType : "json",
			data : input,
			success : function(response) {
			  
				$("." + response.type).html(response.message)
				$("." + response.type).show();
				$("#frm-mobile-verification").html("").hide();
				
			},
			error : function() {
				alert("Error");
			}
		});
	} else {
		$(".err").html('You have entered wrong OTP.')
		$(".err").show();
	}
}

Server sends otp to email id

On receiving a request sever generates a random otp and stores it in the session variable for later verification. We call php mail() function here to send email to the given id. After that, we include the otp-verification.php form and send it back to the client as an ajax response. The user enters received otp in the otp-verification.php page.

controller.php

<?php

session_start();
error_reporting(E_ALL & ~ E_NOTICE);

class Controller
{
    function __construct() {
        $this->processEmailVerification();
    }
    function processEmailVerification()
    {
        switch ($_POST["action"]) {
            
            case "get_otp":
                $email = $_POST['email'];
                $otp = rand(100000, 999999); //generates random otp
                $_SESSION['session_otp'] = $otp;
                $message = "Your one time email verification code is" . $otp;
                $sub = "Email verification from Dj Techblog";
                $headers = "From : " . "dj@djtechblog.com";
                try{
                    $retval = mail($email,$sub,$message);
                    if($retval)
                    {
                        require_once('otp-verification.php');
                    }
                }
                
                catch(Exception $e)
                {
                    die('Error: '.$e->getMessage());
                }
 
                break;
                
            case "verify_otp":
                $otp = $_POST['otp'];
                
                if ($otp == $_SESSION['session_otp']) 
                {
                   unset($_SESSION['session_otp']);
                   echo json_encode(array("type"=>"success", "message"=>"Your Email is verified!"));
                } 
                else {
                    echo json_encode(array("type"=>"error", "message"=>"Mobile Email verification failed"));
                }
                break;
        }
    }
}
$controller = new Controller();
?>
                             

User verifies the received otp

After entering otp when the user hits on the verify button a separate javascript function is called. This function checks the length of the otp field, if it matches the desired length, it makes another ajax request to the server with the otp as input. On receiving the otp server checks it with the stored otp in the session variable. After matching both the otp value server responds accordingly.

otp-verification.php

<div class="err"></div>
<div class="success"></div>
<form id="#mobile-number-verification">
	<div class="mobile-row">
		<label>OTP is sent to Your Email id</label>		
	</div>

	<div class="mobile-row">
		<input type="number"  id="mobileOtp" class="mobile-input" placeholder="Enter the OTP">		
	</div>

	<div class="mobile-row">
		<input id="verify" type="button" class="btnVerify" value="Verify OTP" onClick="verifyOTP();">		
	</div>
</form>

Download the style.css file from here.

Also read, Simple login form in ajax and php using mobile number.

If you face any issue while implementing the code, you can contact me. Thanks for patient reading.

Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.