I hope that this can help you to make your applications more secure. 2-Step Verification adds one more step into the authentication process and therefore provides a mechanism to provide more security for your systems.
Below is example of 2-Step Verification adding new contact or update existing contact using Twilio API within a 5 simple step and code.
Directory Structure
Root directory
include
images (include ventures-loading.gif file in this folder.)
Create Twilio Account
1) Create to https://www.twilio.com/try-twilio to sign up for your free trial account.
2) Once you finish signup, you should see your Console Dashboard. This is your home for finding your Twilio credentials, checking your usage, procuring a phone number and more.
3) We give you a small preloaded balance to test out Twilio’s functionality. You will not be charged for Twilio phone numbers or usage until you upgrade.
How to Work with your Free Twilio Trial Account
When you signed up for your trial account please visit Twilio document file.
Download Twilio PHP Helper Library
Please visit Twilio PHP Document and follow step by step guidance. And download in your project folder (EX: your project folder/include folder/lib folder/ download twilio library folder ).
User Table
User table contains all the users registration details, here you have to store user details.
CREATE TABLE `user` (
`id` int NOT NULL PRIMARY KEY AUTO_INCREMENT ,
` email_id ` varchar(255) NOT NULL UNIQUE,
` password ` varchar(200) NOT NULL ,
` mobile `bigint(20) NOT NULL,
` is_verification`enum('true', 'false') False
);
Create index.php File
<?php
session_start();
if(isset($_SESSION['login']) && $_SESSION['login']==true){
header("location:home.php");exit;
}
include_once 'include/user.php';
$user = new User();
if (isset($_POST['submit'])) {
$login = $user->check_login($_POST['email'], $_POST['pass']);
if ($login) {
// Registration Success
header("location:verification.php");exit;
} else {
// Registration Failed
echo 'Wrong username or password';
}
}
?>
<!doctype html>
<html lang="en">
<?php include_once 'include/header.php'; ?>
<body>
<div class="container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="card card-signin my-5">
<div class="card-body">
<h5 class="card-title text-center">Sign In</h5>
<form class="form-signin" action="" method="post" name="login">
<div class="form-label-group mb-3">
<label for="inputEmail">Email address</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
</div>
<div class="form-label-group mb-3">
<label for="inputPassword">Password</label>
<input type="password" name="pass" id="inputPassword" class="form-control" placeholder="Password" required>
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase" name="submit" value="Login" type="submit">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
<?php include_once 'include/script.php'; ?>
</body>
</html>
header.php
Create header.php file in include folder, And copy below code.
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title>Login</title>
<style type="text/css">
.error{color:red;}
.error1{color:red;}
</style>
</head>
script.php
Create script.php file in include folder, And copy below code.
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
db_config.php
Create db_config.php file in include folder. Database connection configuration file, here you have to modify username, password and database details.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');// database user name
define('DB_PASSWORD', '');// database password
define('DB_DATABASE', 'loginwithotp'); //database name
class DB_con {
public $connection;
function __construct(){
$this->connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE);
if ($this->connection->connect_error) die('Database error -> ' . $this->connection->connect_error);
}
function ret_obj(){
return $this->connection;
}
}
?>
user.php
This class file, all business logic mention in this file.
<?php
include "db_config.php";
class User{
protected $db;
public function __construct(){
$this->db = new DB_con();
$this->db = $this->db->ret_obj();
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$query = "SELECT id from user WHERE email_id='$emailusername' and password='$password'";
$result = $this->db->query($query) or die($this->db->error);
$user_data = $result->fetch_array(MYSQLI_ASSOC);
$count_row = $result->num_rows;
if ($count_row == 1) {
unset($_SESSION['otpverify']);
unset($_SESSION['uid']);
$_SESSION['otpverify'] = true;
$_SESSION['uid'] = $user_data['id'];
/*$_SESSION['login'] = true; // this login var will use for the session thing
*/
return true;
}else{
return false;
}
}
public function getData($uid=null){
$query = "SELECT * from user WHERE id='$uid'";
$result = $this->db->query($query) or die($this->db->error);
$user_data = $result->fetch_array(MYSQLI_ASSOC);
return $user_data;
}
public function updateOtpStatus($vmblno=null,$uid=null){
$q="UPDATE user SET mobile='$vmblno', is_verification = 'true' WHERE id='$uid'";
$result=$this->db->query($q);
return $result;
}
/*** starting the session ***/
public function get_session(){
$login=(isset($_SESSION['login']))?$_SESSION['login']:'';
$otpverify=(isset($_SESSION['otpverify']))?$_SESSION['otpverify']:'';
$authenticate=array('login' => $login, 'otpverify'=> $otpverify) ;
return $authenticate;
}
public function user_logout() {
$_SESSION['login'] = FALSE;
unset($_SESSION);
session_destroy();
}
}
?>
verification.php
This file is mobile verification front end file.
<?php
session_start();
include_once 'include/user.php';
$user = new User();
$uid = $_SESSION['uid'];
$auth=$user->get_session();
if (!$auth['otpverify'] || !$uid){
header("location:http://localhost/Loginwithotp/"); //Add your home page link
}
$setData=$user->getData($uid);
?>
<!doctype html>
<html lang="en">
<?php include_once 'include/header.php'; ?>
<body>
<div class="container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="error1" style="margin-top:20px"></div>
<div class="success1" style="margin-top:20px"></div>
<div class="card card-signin my-5">
<div class="card-body">
<h5 class="card-title text-center">2 step verification</h5>
<form class="form-signin" name="mverification" id="verifymobileNo">
<input type="hidden" name="action" value="verifyMobile">
<div class="form-label-group mb-3">
<label for="inputEmail">Mobile Number</label>
<input type="tel" name="mobileNo" id="mobileNo" pattern="^\d{12}$" class="form-control" placeholder="EX:911234567890" required autofocus>
<label for="mobileNo" generated="true" class="error" style="display: none;">This field is required.</label>
</div>
<button type="button" class="btn btn-lg btn-primary btn-block text-uppercase" id="submitbtn">Send otp <img src="./images/ventures-loading.gif" class="verifysppiner" style="display:none;margin: auto;width: 28px;float: right;"></button>
</form>
<form id="verifyotp" style="display:none">
<div class="modal-body">
<div class="form-group">
<label for="otpPost" style="float: left;width: 100%;" class="normal-font">Mobile OTP.</label>
<input type="text" class="form-control number required" name="otpPost" id="otpPost" placeholder="Enter Mobile OTP." value="" >
<input type="hidden" name="vmobileNo" id="vmobileNo" class="vmobileNo" value="">
<div class="row clear">
<div class="col-md-12 ">
<label for="vmobileNo" generated="true" class="error" style="display: none;">This field is required.</label>
<span onclick="resendotp();" class="btn resendotp float-right"><img src="./images/ventures-loading.gif" class="resendspinner" style="display: none;width: 20px;float: right;margin-top: 9px;margin-left: 0px;"> Re-Send OTP</span>
</div>
<br/>
<br/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="Otpbtn" class="btn btn-primary">Verify OTP <img src="./images/ventures-loading.gif" class="verifysppiner" style="display:none;margin: auto;width: 20px;float: right;"></button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<?php include_once 'include/script.php'; ?>
</body>
</html>
<script type="text/javascript">
function resendotp(){
$(".resendspinner").show();
//$(".mailsend").hide();
$.post("mobileverification.php", $("#verifymobileNo").serialize(),function(res){
$(".resendspinner").hide();
if(result.sid!="" && result.sid !=undefined){
$(".resendspinner").hide();
}else{
$(".error1").html(result.error1);
$( ".error1" ).focus();
$(".error1").show();
$(".verifysppiner").hide();
}
});
}
$("#submitbtn").click(function(){
$(".verifysppiner").show();
var mobileNo = $("#mobileNo").val();
if(mobileNo==""){
$(".error").show();
$( ".error1" ).focus();
$(".verifysppiner").hide();
return false;
}
var uid=<?=$uid?>;
$.post("mobileverification.php", $("#verifymobileNo").serialize(), function(data) {
var result=jQuery.parseJSON(data);
if(result.sid!="" && result.sid !=undefined){
$("#verifymobileNo").hide();
$("#verifyotp").show();
$(".verifysppiner").hide();
}else{
$(".error1").html(result.error1)
$( ".error1" ).focus();
$(".error1").show();
$(".verifysppiner").hide();
}
});
});
$("#Otpbtn").click(function(){
$(".verifysppiner").show();
if($("#otpPost").val()=="" ){
$(".error").show();
$( ".error" ).focus();
$(".verifysppiner").hide();
return false;
}
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#otpPost").val();
var uid=<?=$uid?>;
var vmblno = $(".vmobileNo").val();
$.post("mobileverification.php", { otp:otp,uid:uid,vmblno:vmblno,action:"verifyotp" }, function(data) {
var result=jQuery.parseJSON(data);
if(result.type=="success1"){
window.location.href="http://localhost/Loginwithotp/home.php"; //Add after login Dashboard link
}else{
$(".error1").html("<span>OTP vitrifaction field</span>");
$( ".error1" ).focus();
$(".verifysppiner").hide();
}
});
});
</script>
mobileverification.php
This is backend file for mobile verification.
<?php
require_once("include/lib/twilio/vendor/autoload.php");
use Twilio\Rest\Client;
session_start();
include_once 'include/user.php';
$user = new User();
$uid = $_SESSION['uid'];
$auth=$user->get_session();
if (!$auth['otpverify'] || !$uid){
header("location:http://localhost/Loginwithotp/"); //Add your home page link
}
if (isset($_GET['logout'])){
$user->user_logout();
header("location:login.php");
}
switch ($_POST["action"]) {
case "verifyMobile":
if($_POST["mobileNo"]!=""){
try{
// Your Account SID and Auth Token from twilio.com/console
unset( $_SESSION['mblotp']);
$sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //twilio account SID.
$token = 'your_auth_token';//twilio account token.
$client = new Client($sid, $token);
$_SESSION['mobileNmbr']=$_POST["mobileNo"];
$mobile_number = "+".$_POST["mobileNo"];
$otp = rand(100000, 999999);
$_SESSION['mblotp'] = $otp;
// Use the client to do fun stuff like send text messages!
$message = $client->messages
->create("$mobile_number", // to
array(
// A Twilio phone number you purchased at twilio.com/console
"from" => "+12562429196",
// the body of the text message you'd like to send
"body" => "Your Verification Number is ".$otp
)
);
$status=array("sid"=>$message->sid);
echo json_encode($status);exit;
}catch(Exception $e){
$status=array("status"=>"false","error1"=>$e->getMessage());
echo json_encode($status);exit;
}
}
$status=array("sid"=>"");
echo json_encode($status);exit;
break;
case "verifyotp":
if(isset($_POST["vmblno"]) && $_POST["otp"] == $_SESSION['mblotp']){
$result= $user->updateOtpStatus($_SESSION['mobileNmbr'],$_POST["uid"]);
if($result){
$_SESSION['login'] = true;
unset($_SESSION['otp']);
unset($_SESSION['mobileNmbr']);
echo json_encode(array("type"=>"success1", "message"=>"Your mobile number is verified!"));
}
} else {
//Session::set('msg', 'Record inserted successfully.');
echo json_encode(array("type"=>"error1", "message"=>"Mobile number verification failed"));
}
break;
}
?>
home.php
Actually this is welcome page after login user redirect in this page.
<?php
session_start();
include_once 'include/user.php';
$user = new User();
$uid = $_SESSION['uid'];
$auth=$user->get_session();
if (!$auth['otpverify'] || !$uid || $_SESSION['login']!=true){
header("location:http://localhost/Loginwithotp/"); //Add your home page link
}
if (isset($_GET['logout']) && $_GET['logout']=='logout'){
$user->user_logout();
header("location:http://localhost/Loginwithotp/"); //Add your home page link
}
?>
<!doctype html>
<html lang="en">
<?php include_once 'include/header.php'; ?>
<body>
<nav class="navbar navbar-expand-lg navbar-light">
<div class="container"><a href="https://gatetouch.com" class="navbar-brand">Demo</a>
<div class="d-flex ml-auto">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#globalNavbar" aria-controls="globalNavbar" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
</div>
<div class="collapse navbar-collapse" id="globalNavbar">
<ul class="navbar-nav d-none d-lg-flex ml-2 order-3">
<li class="nav-item"><a class="nav-link" href="http://localhost/Loginwithotp/home.php?logout=logout">Logout</a></li> <!-- Replace http://localhost/Loginwithotp/home.php to your login dashboard link -->
</ul>
<ul class="navbar-nav d-lg-none">
<li class="nav-item-divider"></li>
<li class="nav-item"><a class="nav-link" href="http://localhost/Loginwithotp/home.php?logout=logout">Logout</a></li><!-- Replace http://localhost/Loginwithotp/home.php to your login dashboard link -->
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<h1>Login Successfully</h1>
</div>
</div>
</div>
<?php include_once 'include/script.php'; ?>
</body>
</html>
Thank you and comment here if you still causing any issues. you are the best 🙂
Leave a Reply