Skip to content
pakainfo

Pakainfo

Web Development & Good Online education

  • Home
  • Blog
  • Categories
  • Tools
  • Full Form
  • Guest Post
  • Advertise
  • About
  • Contact Us

PHP Google Multi factor authentication Tutorial With Example

May 3, 2019 Pakainfo Programming, Mysql, Mysqli, php Leave a comment

Today, We want to share with you PHP Google Multi factor authentication Tutorial With Example from scratch.In this post we will show you enable two factor authentication gmail, hear for Google Multi factor authentication in PHP we will give you demo and example for implement.In this post, we will learn about php 2 factor authentication google authenticator with an example.

PHP Google Multi factor authentication Tutorial With Example from scratch

Contents

  • PHP Google Multi factor authentication Tutorial With Example from scratch
    • Step 1 Google Authenticator Application Install
    • Step 2 Database Configuration
    • Step 3 Database Connection Script
    • Step 4 SignUp Page
    • Step 5 SignIn Page
    • Step 6 Create Library file
    • Step 7 Member SignUp
    • Step 8 Member Device Conformation
    • Step 9 Create profile page
    • Step 10 SignIn Script
    • Step 11 Validated Security Code
    • Step 12 Member Logout
    • Read
    • Summary
    • Related posts

There are the Following The simple About PHP Google Multi factor authentication Tutorial With Example from scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop google 2 factor authentication new phone, so the 2 factor authentication php for this example is following below.

Step 1: Google Authenticator Application Install

Free Download and Install Google Authenticator Application:

Step 2: Database Configuration:

store Google Secret Code.

CREATE TABLE `members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `membername` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(250) NOT NULL,
  `live_code_key_google_secret` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
);

Step 3: Database Connection Script:

app_config/database_config.php

 PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => FALSE,
        );
        $dsn = 'mysql:host=' . HOST . ';dbname=' . DATABASE . ';charset=' . CHARSET;
        $instance = new PDO($dsn, USER, PASSWORD, $opt);
    }
    return $instance;
}

?>

Step 4: SignUp Page:

signup.php



    
    <title>SignUp - Google Multi factor authentication in PHP</title>
    



<div class="container">
    <div class="row jumbotron">
        <div class="col-md-12">
            <h2>
                Demo: Using Google Two factor authentication in PHP
            </h2>
            <p>
                Note: This is demo version from Pakainfo Empires tutorials. (Multi-factor Authentication)
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-5 col-md-offset-3 well">
            <h4>SignUp</h4>
            <?php
            if ($signup_error_message != "") {
                echo '<div class="alert alert-danger"><strong>Error: </strong> ' . $signup_error_message . '</div>';
            }
            ?>
            <form action="signup.php" method="post">
                <div class="pakainfo form-group  gst">
                    <label for="">Name</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    <label for="">Email</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    <label for="">Membername</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    <label for="">Password</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    
                </div>
            </form>
            <div class="pakainfo form-group  gst">
                Click here to <a href="index.php">SignIn</a> if you have already registred your account.
            </div>
        </div>
    </div>
</div>



Step 5: SignIn Page:

index.php



    
    <title>SignIn - Google Multi factor authentication in PHP</title>
    <!-- Latest compiled and minified CSS -->
    



<div class="container">
    <div class="row jumbotron">
        <div class="col-md-12">
            <h2>
                Demo google authentication php: Using Google Two factor authentication in PHP
            </h2>
            <p>
                Note: This is demo version from Pakainfo Empires tutorials. (Multi-factor Authentication)
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-5 col-md-offset-3 well">
            <h4>SignIn</h4>
            <?php
            if ($login_error_message != "") {
                echo '<div class="pakainfo alert alert-danger"><strong>Error: </strong> ' . $login_error_message . '</div>';
            }
            ?>
            <form action="index.php" method="post">
                <div class="pakainfo form-group  gst">
                    <label for="">Membername/Email</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    <label for="">Password</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    
                </div>
            </form>
            <div class="pakainfo form-group  gst">
                Not Registered Yet? <a href="signup.php">SignUp Here</a>
            </div>
        </div>
    </div>
</div>



Step 6: Create Library file:

googleauthlibs/googleauthlibs.php

db = $db;
    }

    function __destruct()
    {
        $this->db = null;
    }

    public function SignUp($name, $email, $membername, $password, $live_code_key_google_secret)
    {
        $sql_query = $this->db->prepare("INSERT INTO members(name, email, membername, password, live_code_key_google_secret) VALUES (:name,:email,:membername,:password,:live_code_key_google_secret)");
        $sql_query->bindParam("name", $name, PDO::PARAM_STR);
        $sql_query->bindParam("email", $email, PDO::PARAM_STR);
        $sql_query->bindParam("membername", $membername, PDO::PARAM_STR);
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $sql_query->bindParam("password", $hash, PDO::PARAM_STR);
        $sql_query->bindParam("live_code_key_google_secret", $live_code_key_google_secret, PDO::PARAM_STR);
        $sql_query->execute();
        return $this->db->lastInsertId();
    }
    public function isMembername($membername)
    {
        $sql_query = $this->db->prepare("SELECT id FROM members WHERE membername=:membername");
        $sql_query->bindParam("membername", $membername, PDO::PARAM_STR);
        $sql_query->execute();
        if ($sql_query->rowCount() > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function isEmail($email)
    {
        $sql_query = $this->db->prepare("SELECT id FROM members WHERE email=:email");
        $sql_query->bindParam("email", $email, PDO::PARAM_STR);
        $sql_query->execute();
        if ($sql_query->rowCount() > 0) {
            return true;
        } else {
            return false;
        }
    }

    public function SignIn($membername, $password)
    {
        $sql_query = $this->db->prepare("SELECT id, password FROM members WHERE membername=:membername OR email=:email");
        $sql_query->bindParam("membername", $membername, PDO::PARAM_STR);
        $sql_query->bindParam("email", $membername, PDO::PARAM_STR);
        $sql_query->execute();
        if ($sql_query->rowCount() > 0) {
            $result = $sql_query->fetch(PDO::FETCH_OBJ);
            $enc_password = $result->password;
            if (password_verify($password, $enc_password)) {
                return $result->id;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function MemberDetails($member_id)
    {
        $sql_query = $this->db->prepare("SELECT id, name, membername, email, live_code_key_google_secret FROM members WHERE id=:member_id");
        $sql_query->bindParam("member_id", $member_id, PDO::PARAM_STR);
        $sql_query->execute();
        if ($sql_query->rowCount() > 0) {
            return $sql_query->fetch(PDO::FETCH_OBJ);
        }
    }
}

Step 7: Member SignUp:

signup.php

createSecret();

$signup_error_message = '';

// check SignUp request
if (!empty($_POST['btnRegister'])) {
    if ($_POST['name'] == "") {
        $signup_error_message = 'Name field is required!';
    } else if ($_POST['email'] == "") {
        $signup_error_message = 'Email field is required!';
    } else if ($_POST['membername'] == "") {
        $signup_error_message = 'Membername field is required!';
    } else if ($_POST['password'] == "") {
        $signup_error_message = 'Password field is required!';
    } else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $signup_error_message = 'Invalid email address!';
    } else if ($app->isEmail($_POST['email'])) {
        $signup_error_message = 'Email is already in use!';
    } else if ($app->isMembername($_POST['membername'])) {
        $signup_error_message = 'Membername is already in use!';
    } else {
        $member_id = $app->SignUp($_POST['name'], $_POST['email'], $_POST['membername'], $_POST['password'], $secret);
        $_SESSION['member_id'] = $member_id;
        header("Location: confirm_google_auth.php");
    }
}
?>

Step 8: Member Device Conformation:

confirm_google_auth.php

MemberDetails($_SESSION['member_id']);

require_once __DIR__ . '/GoogleAuthenticator/GoogleAuthenticator.php';
$PHPGoogleAuth = new PHPGangsta_GoogleAuthenticator();
$qr_code =  $PHPGoogleAuth->getQRCodeGoogleUrl($member->email, $member->live_code_key_google_secret, 'pakainfo.com');

$live_msg_error_alert = '';

if (isset($_POST['validateBtn'])) {

    $code = $_POST['code'];

    if ($code == "") {
        $live_msg_error_alert = 'Please Scan above QR code to configure your application and enter genereated authentication code to validated!';
    }
    else
    {
        if($PHPGoogleAuth->verifyCode($member->live_code_key_google_secret, $code, 2))
        {
            header("Location: profile.php");
        }
        else
        {
            $live_msg_error_alert = 'Invalid Authentication Code!';
        }
    }
}
?>



    
    <title>Confirm Member Device</title>
    



<div class="container">
    <div class="row jumbotron">
        <div class="col-md-12">
            <h2>
                Demo: Using Google Two factor authentication in PHP
            </h2>
            <p>
                Note: This is demo version from Pakainfo Empires tutorials. (Multi-factor Authentication)
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-5 col-md-offset-3 well">
            <h4>Application Authentication</h4>

            <p>
                Please download and install Google authenticate app on your phone, and scan following QR code to configure your device.
            </p>

            <div class="pakainfo form-group  gst">
                <img src="">
            </div>

            <form method="post" action="confirm_google_auth.php">
                <?php
                if ($live_msg_error_alert != "") {
                    echo '<div class="alert alert-danger"><strong>Error: </strong> ' . $live_msg_error_alert . '</div>';
                }
                ?>
                <div class="pakainfo form-group  gst">
                    <label for="code">Enter Authentication Code:</label>
                    
                </div>
                <div class="pakainfo form-group  gst">
                    <button type="submit" name="validateBtn" class="btn btn-primary">Validate</button>
                </div>
            </form>

            <div class="pakainfo form-group  gst">
                Click here to <a href="index.php">SignIn</a> if you have already signuped your account.
            </div>
        </div>
    </div>
</div>



Step 9: Create profile page:

profile.php

MemberDetails($_SESSION['member_id']);

?>



    
    <title>Member Profile</title>
    



<div class="container">
    <div class="row jumbotron">
        <div class="col-md-12">
            <h2>
                Demo: Using Google Two factor authentication in PHP
            </h2>
            <p>
                Note: This is demo version from Pakainfo Empires tutorials. (Multi-factor Authentication)
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-5 col-md-offset-3 well">
            <h2>Member Profile</h2>
            <h4>Welcome name; ?></h4>
            <p>Account Details:</p>
            <p>Name: name; ?></p>
            <p>Membername membername; ?></p>
            <p>Email email; ?></p>
            <br>
            Click here to <a href="logout.php">Logout</a>
        </div>
    </div>
</div>



Step 10: SignIn Script:

index.php

SignIn($membername, $password);
        if($member_id > 0)
        {
            $_SESSION['member_id'] = $member_id;
            header("Location: validate_login.php");
        }
        else
        {
            $login_error_message = 'Invalid login details!';
        }
    }
}
?>

Step 11: Validated Security Code:

validate_login.php

MemberDetails($_SESSION['member_id']);

require_once __DIR__ . '/GoogleAuthenticator/GoogleAuthenticator.php';
$PHPGoogleAuth = new PHPGangsta_GoogleAuthenticator();

$live_msg_error_alert = '';

if (isset($_POST['validateBtn'])) {

    $code = $_POST['code'];

    if ($code == "") {
        $live_msg_error_alert = 'Please enter authentication code to validated!';
    }
    else
    {
        if($PHPGoogleAuth->verifyCode($member->live_code_key_google_secret, $code, 2))
        {
            // success
            header("Location: profile.php");
        }
        else
        {
            // fail
            $live_msg_error_alert = 'Invalid Authentication Code!';
        }
    }
}
?>



    
    <title>Validate SignIn</title>
    <!-- Latest compiled and minified CSS -->
    



<div class="container">
    <div class="row jumbotron">
        <div class="col-md-12">
            <h2>
                Demo: Using Google Two factor authentication in PHP
            </h2>
            <p>
                Note: This is demo version from Pakainfo Empires tutorials. (Multi-factor Authentication)
            </p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-5 col-md-offset-3 well">
            <h4>Multi Factor Authentication</h4>

            <form method="post" action="validate_login.php">
                <?php
                if ($live_msg_error_alert != "") {
                    echo '<div class="alert alert-danger"><strong>Error: </strong> ' . $live_msg_error_alert . '</div>';
                }
                ?>
                <div class="pakainfo form-group  gst">
                    
                </div>
                <div class="pakainfo form-group  gst">
                    <button type="submit" name="validateBtn" class="btn btn-primary">Validate</button>
                </div>
            </form>

            <div class="pakainfo form-group  gst">
                Click here to <a href="index.php">SignIn</a> if you have already signuped your account.
            </div>
        </div>
    </div>
</div>



Step 12: Member Logout:

logout.php

Angular 6 CRUD Operations Application Tutorials

Read :

  • Technology
  • Google Adsense
  • Programming
Also Read This ๐Ÿ‘‰   Convert Array to XML and XML to Array using PHP

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Google Multi factor authentication Tutorial With Example from scratch.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donโ€™t forget to share.

Related posts:

  1. laravel multi auth (Authentication) guards Example
  2. Laravel Multiple Authentication Example
Also Read This ๐Ÿ‘‰   Vue js call function on page load Example
2 factor authentication phpadd two factor authentication to websiteenable two factor authentication gmailgoogle 2 factor authentication new phonegoogle authentication phpgoogle authenticator developer phpgoogle authenticator phpgoogle two factor authentication apigoogle2fa phphow to implement two factor authenticationlaravel 2faphp 2 factor authentication google authenticatorphp 2 factor authentication smsphp 2-step login verificationtwo factor authentication implementation plan

Post navigation

Previous Post:Stripe API subscriptions with plan coupon and discounts using PHP
Next Post:Vuejs Filter Currency Round to 2 decimal places

Advertise With Us

Increase visibility and sales with advertising. Let us promote you online.
Click Here

Write For Us

Weโ€™re accepting well-written informative guest posts and this is a great opportunity to collaborate.
Submit a guest post to [email protected]
Contact Us

Freelance web developer

Do you want to build a modern, lightweight, responsive website quickly?
Need a Website Or Web Application Contact : [email protected]
Note: Paid Service
Contact Me

Categories

3movierulz (64) Ajax (464) AngularJS (377) ASP.NET (61) Bio (109) Bollywood (108) Codeigniter (175) CSS (98) Earn Money (69) Education (61) Entertainment (130) fullform (86) Google Adsense (63) Highcharts (77) History (40) Hollywood (109) JavaScript (1357) Jobs (42) jQuery (1423) Laravel (1088) LifeStyle (53) movierulz4 (63) Mysql (1029) Mysqli (890) php (2121) Programming (2332) Python (98) Software (167) Software (88) Stories (98) tamilrockers (104) Tamilrockers kannada (64) Tamilrockers telugu (61) Tech (142) Technology (2392) Tips and Tricks (119) Tools (205) Top10 (483) Trading (91) Trending (71) VueJs (250) Web Technology (105) webtools (191) wordpress (166) World (324)

A To Z Full Forms

Access a complete full forms list with the meaning, definition, and example of the acronym or abbreviation.
Click Here
  • Home
  • About Us
  • Terms And Conditions
  • Write For Us
  • Advertise
  • Contact Us
  • Youtube Tag Extractor
  • Info Grepper
  • Guest Posting Sites
  • Increase Domain Authority
  • Social Media Marketing
  • Freelance web developer
  • Tools
Pakainfo 9-OLD, Ganesh Sco, Kothariya Ring Road, Chokadi, Rajkot - 360002 India
E-mail : [email protected]
Pakainfo

ยฉ 2023 Pakainfo. All rights reserved.

Top
Subscribe On YouTube : Download Source Code
We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype Guest Posting Sites