OTP Verification

Tips submitted by PHPMaker users
Post Reply
Niijimasama
User
Posts: 85

OTP Verification

Post by Niijimasama »

PLEASE NOTE, I AM USING SWEET ALERTS. CAN'T ADD CODE DUE TO FORUM MOD SECURITY.

I make alot of PWAs using PHPmaker and OTP verification is something I have been looking to add to my applications.
The below code works for me currently but I would appreciate input in making it better.

  1. Create table to store OTP CODES.
    CREATE TABLE otp_ver (
    o_id INT(10) NOT NULL AUTO_INCREMENT,
    u_code INT(10) NULL DEFAULT NULL,
    s_code TEXT NULL,
    v_code TEXT NULL,
    o_status ENUM('Y','N') NULL DEFAULT NULL,
    PRIMARY KEY (o_id)
    )
    COLLATE='utf8mb4_general_ci'

  2. Create Function to Generate Random String (OTP CODE)

function GenerateRandomString($length = 5) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

  1. Create a function to sms OTP Code (modify to suit your provider)

function Send_OTP($uname){
$otp = GenerateRandomString();
$uphonesql = "select user_id,user_phone from app_users where user_name = '".$uname."'";
$uphone = ExecuteRow($uphonesql);
$otpinsert = "insert into otp_ver(u_code,s_code,o_status)
values(".$uphone["user_id"].",'".$otp."','N')";
Execute($otpinsert);
$otptxt = "Thank you for Registering on Shopman.
Your Username is ".$userinfo["user_name"].".
Your OTP is ".$otp." . Login to verify your code.
Thank You.";
$sendto = $uphone["user_phone"];
SendSMS($sendto, $otptxt);
}

  1. Create function to verify OTP status when logging in. It will redirect user to verification page if code is not verified

function Check_OTP($uname){
$ucodesql = "select user_id from app_users where user_name = '".$uname."'";
$ucode = ExecuteScalar($ucodesql);
$otpsql = "select o_status from otp_ver where u_code = ".$ucode."";
$tstatus = ExecuteScalar($otpsql);
if ($tstatus == 'Y')
{
return TRUE;
}
elseif ($tstatus == 'N')
{

	$_SESSION[SESSION_STATUS] = "";
	ob_end_clean();
	// NOTE: Modify the target page
	header("Location:otp/otp_verify.php");
	exit();
	return FALSE;
	//setFailureMessage("Sorry! User Not verified.");
}
else
{		
	$_SESSION = [];
}		

}

  1. Go to Server Events-> Table Specific-> Common-> Row Inserted OF USERS TABLE and add the code below:

if(CurrentPageID() == "register"){
Send_OTP($rsnew["user_name_column"]);

}
  1. Go to Server Events-> Other-> Login Page-> User_loggingIn OF USERS TABLE and add the code below:

Check_OTP($usr);

7.a) Create a db configuration file, in my case 'conn.php'.

b) Create a custom file "otp_verifier.php" for processing the OTP Code Verification and add the code below.

<?php
include '../conn.php';

$otp_code = mysqli_real_escape_string($con,$_POST['otp_code']);

if ($otp_code != ""){
//CHECK IF SIMILAR OTP CODE EXISTS
$sql_query = "select * from otp_ver where s_code = '".$otp_code."' and o_status = 'N'";
//$sql_query = "select * from otp_ver where s_code = '".$otp_code."'";
$result = $con->query($sql_query);
$row = $result->fetch_assoc();
//if(strcmp($otp_code, $row["s_code"]) == 0){

$otpuser = $con->query("select user_name from app_users where user_id = ".$row["u_code"]."");
	
if(!empty($otpuser)){	
	if(($row["o_status"] == 'N')){
		$otpupdate = "update otp_ver 
						SET	v_code = '".$otp_code."',
							o_status = 'Y'
							where s_code = '".$row["s_code"]."'";
		$con->query($otpupdate);
			
		//$_SESSION['uname'] = $uname;
		echo 1;
	}elseif(($row["o_status"] == 'Y')){
		mysqli_error();
		echo 0;
	}
}else{
	echo 2;
}

}

?>

  1. Create a custom file "otp_verify.php" for entering the OTP Code for Verification:

<!DOCTYPE html>

<html>
<head>
<title>OTP Verify</title>
<!-- Site icon -->
<link rel="icon" href="shopman_logo.png">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

//Add script refs for jquery, botstrap, sweetalerts & fontawesome

<style>

/* BASIC */

html {
  background-color: #56baed;
}

body {
  font-family: "Poppins", sans-serif;
  height: 100vh;
}

a {
  color: #92badd;
  display:inline-block;
  text-decoration: none;
  font-weight: 400;
}

h2 {
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  text-transform: uppercase;
  display:inline-block;
  margin: 40px 8px 10px 8px; 
  color: #cccccc;
}



/* STRUCTURE */

.wrapper {
  display: flex;
  align-items: center;
  flex-direction: column; 
  justify-content: center;
  width: 100%;
  min-height: 100%;
  padding: 20px;
}

#formContent {
  -webkit-border-radius: 10px 10px 10px 10px;
  border-radius: 10px 10px 10px 10px;
  background: #fff;
  padding: 30px;
  width: 90%;
  max-width: 450px;
  position: relative;
  padding: 0px;
  -webkit-box-shadow: 0 30px 60px 0 rgba(0,0,0,0.3);
  box-shadow: 0 30px 60px 0 rgba(0,0,0,0.3);
  text-align: center;
}

#formFooter {
  background-color: #f6f6f6;
  border-top: 1px solid #dce8f1;
  padding: 25px;
  text-align: center;
  -webkit-border-radius: 0 0 10px 10px;
  border-radius: 0 0 10px 10px;
}



/* TABS */

h2.inactive {
  color: #cccccc;
}

h2.active {
  color: #0d0d0d;
  border-bottom: 2px solid #5fbae9;
}



/* FORM TYPOGRAPHY*/

input[type=button], input[type=submit], input[type=reset]  {
  background-color: #56baed;
  border: none;
  color: white;
  padding: 15px 80px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  text-transform: uppercase;
  font-size: 13px;
  -webkit-box-shadow: 0 10px 30px 0 rgba(95,186,233,0.4);
  box-shadow: 0 10px 30px 0 rgba(95,186,233,0.4);
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
  margin: 5px 20px 40px 20px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -ms-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

input[type=button]:hover, input[type=submit]:hover, input[type=reset]:hover  {
  background-color: #39ace7;
}

input[type=button]:active, input[type=submit]:active, input[type=reset]:active  {
  -moz-transform: scale(0.95);
  -webkit-transform: scale(0.95);
  -o-transform: scale(0.95);
  -ms-transform: scale(0.95);
  transform: scale(0.95);
}

input[type=text] {
  background-color: #f6f6f6;
  border: none;
  color: #0d0d0d;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 5px;
  width: 85%;
  border: 2px solid #f6f6f6;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  -ms-transition: all 0.5s ease-in-out;
  -o-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}

input[type=text]:focus {
  background-color: #fff;
  border-bottom: 2px solid #5fbae9;
}

input[type=text]:placeholder {
  color: #cccccc;
}



/* ANIMATIONS */

/* Simple CSS3 Fade-in-down Animation */
.fadeInDown {
  -webkit-animation-name: fadeInDown;
  animation-name: fadeInDown;
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes fadeInDown {
  0% {
	opacity: 0;
	-webkit-transform: translate3d(0, -100%, 0);
	transform: translate3d(0, -100%, 0);
  }
  100% {
	opacity: 1;
	-webkit-transform: none;
	transform: none;
  }
}

@keyframes fadeInDown {
  0% {
	opacity: 0;
	-webkit-transform: translate3d(0, -100%, 0);
	transform: translate3d(0, -100%, 0);
  }
  100% {
	opacity: 1;
	-webkit-transform: none;
	transform: none;
  }
}

/* Simple CSS3 Fade-in Animation */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

.fadeIn {
  opacity:0;
  -webkit-animation:fadeIn ease-in 1;
  -moz-animation:fadeIn ease-in 1;
  animation:fadeIn ease-in 1;

  -webkit-animation-fill-mode:forwards;
  -moz-animation-fill-mode:forwards;
  animation-fill-mode:forwards;

  -webkit-animation-duration:1s;
  -moz-animation-duration:1s;
  animation-duration:1s;
}

.fadeIn.first {
  -webkit-animation-delay: 0.4s;
  -moz-animation-delay: 0.4s;
  animation-delay: 0.4s;
}

.fadeIn.second {
  -webkit-animation-delay: 0.6s;
  -moz-animation-delay: 0.6s;
  animation-delay: 0.6s;
}

.fadeIn.third {
  -webkit-animation-delay: 0.8s;
  -moz-animation-delay: 0.8s;
  animation-delay: 0.8s;
}

.fadeIn.fourth {
  -webkit-animation-delay: 1s;
  -moz-animation-delay: 1s;
  animation-delay: 1s;
}

/* Simple CSS3 Fade-in Animation */
.underlineHover:after {
  display: block;
  left: 0;
  bottom: -10px;
  width: 0;
  height: 2px;
  background-color: #56baed;
  content: "";
  transition: width 0.2s;
}

.underlineHover:hover {
  color: #0d0d0d;
}

.underlineHover:hover:after{
  width: 100%;
}



/* OTHERS */

*:focus {
	outline: none;
} 

#icon {
  width:60%;
}
</style>
<!------ Include the above in your HEAD tag ---------->

</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<a id="home" href="../index.php" class="btn btn-info" ><i class="nav-icon fa-home fas"></i> </a>
<!-- Icon -->
<div class="fadeIn first">
<img src="robot_user.png" id="icon" alt="User Icon" />
</div>

	<!-- Login Form -->
	<form>
		<h2> Please enter your OTP code</h2>
	  <input type="text" id="otp" class="fadeIn second" name="otp" placeholder="OTP Code" autocomplete="off">
	  <!--input type="text" id="password" class="fadeIn third" name="login" placeholder="password"-->
	  <input type="submit" class="fadeIn fourth" value="Verify" id="verify">
	</form>

	 </div>
</div>

</body>
// Add AJAX CODE SECTION

$(document).ready(function(){
$("#verify").click(function(e){
e.preventDefault();

	var otp_code = $("#otp").val().trim();
	//var password = $("#txt_pwd").val().trim();

	if( otp_code != ""){
		$.ajax({
			url:'otp_verifier.php',
			type:'POST',
			//dataType: "json",
			data:{otp_code:otp_code},
			success:function(response){
				var msg = "";
				
				if(response == 1){
					setTimeout(function () { swal({title:"Awesome!",text:"Code Verified! ",icon:"success",button: "OK!",});
					}, 1000);
					//alert(response);
					//console.log(res.msg);
				   setTimeout("top.location.href = '../index.php'",3000);
				}else if(response == 0){
					setTimeout(function () { swal({title:"Sorry!",text:"Code Already Verified! ",icon:"info",button: "OK!",});
					}, 1000);
					//console.log(res.msg);
					//msg = "Invalid username and password!";
					
				}else{
					setTimeout(function () { swal({title:"Sorry!",text:"Code Does not exist!! ",icon:"error",button: "OK!",});
					}, 1000);
					//console.log(res.msg);
					//msg = "Invalid username and password!";
					setTimeout("top.location.href = '../index.php'",3000);
				}
				$("#message").html(msg);
			}
		});
	}
});

});
</html>

  1. Add Ajax Code to the section marked above for your own verification

Post Reply