Login with Google Account Using PHP & MySQLi (Source Code)

Now a days in the world of internet, as we know social media is an very import part of any web based application. So if your web application has provide feature like login with social media, then it will be gaining more new users to your web application. So, in this post we have share tutorial on how to login or sign in or register with Google Account in your PHP web application. Here we will make system in which user can login with their Google account into your website.

For login with Google Account using PHP, Google has provide Google OAuth API, which is very easy and helpful to you for implement login using Google account into your Website. Google Login API has provide rights to user to login into the website by using their Google account credential without register on that particular website. By using this feature, your website will gain more subscriber, this is because in current days most of all users have a Google Account, so they can login with their Google Account without sign in on your website.

In this tutorial, we will use Google OAuth Login API, this API give permission to users to login with their existing Google accounts to your website. Below you can find how to integrate Google Login API in your PHP website and you can also find the process how to get API key and how to integrate Google Client Library in your existing PHP library for Login.

Get Google API Credential


First we need to get Google API keys, for this first you have Google Account. So, login into your Google Account and follow below step.

1 - Go to https://console.developers.google.com/ this link.

2 - After this click on Create New Project link for create new project.

3 - Enter Project Name and click on Create button.

4 - Once you have create new project then you can see your project list on web page.

5 -After this click on Google API logo for go to home page.

6 - Once you have redirect to home page then select project from the project select box.

7 - After click on project select box, then one modal will popup and under this you can find list of project, so select your project.

8 - Now from left menu, you have to click on OAuth consent screen.
9 - Once you have click on OAuth consent screen, then one page will load, here you have to define application name and after this click on save button.

10 - When you have click on save button, then after page will redirect another page, and here you have to click on Create credential button, so one drop down menu will appear and from this you have to select OAuth client ID

11 - After click on OAuth client ID menu then you have redirect to another page, and here you can find different Application type.


12 - From different Application type option, you have to select Web application. Once you have select Web application option, then one form will appear on web page. Here you have to define Name and you have also define Authorized redirect URIs field and lastly click on Create button.

13 - Once you have click on create button, then you can get your Client ID and your client secret key. You have to copy both key for future use for implement Login using Google account using PHP.

Download Google API Client Library for PHP


After getting Google API key, now we need to download Google API Client Library for PHP. For this we have to go command prompt and first type composer command, after this we need to run following command.

composer require google/apiclient:"^2.0"


This command will download Google API Client Library for PHP in your define directory. Now we have proceed for PHP code for how to use Google API Client Library for login using Google account with PHP.

FILE STRUCTURE



config.php

 

<?php
//Include Google Client Library for PHP autoload file
require_once 'autoload.php';

//Make object of Google API Client for call Google API
$google_client = new Google_Client();

//Set the OAuth 2.0 Client ID
$google_client->setClientId('ENTER CLIENT ID');

//Set the OAuth 2.0 Client Secret key
$google_client->setClientSecret('ENTER CLIENT SECRET');

//Set the OAuth 2.0 Redirect URI
$google_client->setRedirectUri('http://localhost/loginwithgoogle/');
$google_client->addScope('email');
$google_client->addScope('profile');

?>
index.php
<?php
session_start();
//Include Configuration File
include('db.php');
include('vendor/config.php');
error_reporting(0);
$conn = _connectodb();
setTimeZone();
$added_on = date("Y-m-d h:i:s");
$login_button = '';

//This $_GET["code"] variable value received after user has login into their Google Account redirct to PHP script then this variable value has been received
if (isset($_GET["code"])) {

    //It will Attempt to exchange a code for an valid authentication token.
    $token = $client->fetchAccessTokenWithAuthCode($_GET["code"]);

    //This condition will check there is any error occur during geting authentication token. If there is no any error occur then it will execute if block of code

    if (!isset($token['error'])) {
        //Set the access token used for requests
        $client->setAccessToken($token['access_token']);

        //Store "access_token" value in $_SESSION variable for future use.
        $_SESSION['access_token'] = $token['access_token'];

        //Create Object of Google Service OAuth 2 class
        $google_service = new Google_Service_Oauth2($client);

        //Get user profile data from google
        $data = $google_service->userinfo->get();
         if (!empty($data['given_name'])) {
            $_SESSION['user_first_name'] = $data['given_name'];
        }
        if (!empty($data['family_name'])) {
            $_SESSION['user_last_name'] = $data['family_name'];
        }
        if (!empty($data['email'])) {
            $_SESSION['user_email_address'] = $data['email'];
        }
        if (!empty($data['gender'])) {
            $_SESSION['user_gender'] = $data['gender'];
        } else {
            $_SESSION['user_gender'] = '';
        }
        if (!empty($data['picture'])) {
            $_SESSION['user_image'] = $data['picture'];
        }
        if (!empty($data['id'])) {
            $_SESSION['google_id'] = $data['id'];
        }
        $selectemail = "select * from users where google_id='" . $_SESSION['google_id'] . "'";
        $result    = mysqli_query($conn, $selectemail);
        if (mysqli_num_rows($result) == 1) {
        } else {
            $sql = "insert into users (google_id,first_name,last_name,email,gender,pic,added_on) values('" . $_SESSION['google_id'] . "','" . $_SESSION['user_first_name'] . "','" . $_SESSION['user_last_name'] . "','" . $_SESSION['user_email_address'] . "','" . $_SESSION['user_gender'] . "','" . $_SESSION['user_image'] . "','$added_on')";
            $result    = mysqli_query($conn, $sql);
        }
    }
}
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['access_token']);
    header('Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
//This is for check user has login into system by using Google account, if User not login into system then it will execute if block of code and make code for display Login link for Login using Google account.
if (!isset($_SESSION['access_token'])) {
    //Create a URL to obtain user authorization
    $login_button = '<a class="text-white" href="' . $client->createAuthUrl() . '">Sign in with Google</a>';
}
?>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>PHP Login using Google Account</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport' />
    <!-- Latest compiled and minified CSS -->
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        a {
            text-decoration: none !important;
            outline: none !important;
        }
        .logoutbtn {
            background: #fbdd85;
            padding: 8px 20px;
            color: #4d4d4d !important;
        }
    </style>
</head>
<body>
     <div class="container mt-5">
        <div class="row">
            <div class="col-md-5 m-auto">
                <div class="card text-white" style="background: #4b748c !important;">
                    <div class="card-body">
                        <?php
                        if ($login_button == '') {
                            echo '<img src="' . $_SESSION["user_image"] . '" class="img-responsive  img-thumbnail rounded-circle" />';
                            echo '<h5 class="mt-3"><b>Name :</b> ' . $_SESSION['user_first_name'] . ' ' . $_SESSION['user_last_name'] . '</h5>';
                            echo '<h5 class="mb-4"><b>Email :</b> ' . $_SESSION['user_email_address'] . '</h5>';
                            echo '<h6><a href="index.php?logout" class="logoutbtn mt-5">Logout</a></h6>';
                        } else {
                            echo '<div align="center" > ' . $login_button . '</div>';
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Download
17.02 MB