Portal Login with Google Account using PHP : Google OAuth Programming interface gives a simple and strong method for coordinating the login framework on the site. Google Login Programming interface permits the client to sign-in to the site utilizing their Google account without join on that site. Google login framework most certainly assists with expanding the supporters on your site.

Since these days practically all clients have a Google record and they can sign in with their Google account without enlistment on your site. The web designers can undoubtedly carry out the login and enrollment framework in the web application utilizing Google OAuth 2.0 and PHP. In this instructional exercise, we’ll demonstrate the way that you can coordinate client login framework with Google verification utilizing Google Programming interface PHP library.

Here we’ll give the bit by bit manual for carrying out login with Google account involving PHP and store the client data in the MySQL data set. Our model Google login script utilizes the Programming interface PHP Client Library to carry out Login with Google involving PHP in the web application. Prior to beginning to coordinate Login with Google utilizing PHP and MySQL, investigate the records structure.

Create Google API For Google Sign

  • Go to the Google API Console.
  • Select an existing project from the projects list, or click NEW PROJECT to create a new project:
    • Enter the Project Name.
    • Under the Project Name, you will see the Google API console automatically creates a project ID. Optionally you can change this project ID by the Edit link. But project ID must be unique worldwide.
    • Click on the CREATE button and the project will be created in some seconds.
  • In the left side navigation panel, select Credentials under the APIs & Services section.
  • Select the OAuth consent screen tab, specify the consent screen settings.
    • In Application name field, enter the name of your Application.
    • In Support email filed, choose an email address for user support.
    • In the Authorized domains, specify the domains which will be allowed to authenticate using OAuth.
    • Click the Save button.
  • Select the Credentials tab, click the Create credentials drop-down and select OAuth client ID.
    • In the Application type section, select Web application.
    • In the Authorized redirect URIs field, enter the redirect URL.
    • Click the Create button.

A dialog box will appear with OAuth client details, note the Client ID and Client secret. This Client ID and Client secret allow you to access the Google APIs.

 

Portal Login with Google Account using PHP

To log in to any of your portals from Google, you can apply this method by following the steps given below-

Create Database Table

To store the user account information from Google, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database to hold the Google profile information.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('google','facebook','twitter','linkedin') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'google',
 `oauthtoken` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `verifiedEmail` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create config.php Files

config.php In this file, you have to set setClientId and setClientSecret key generated by Google Console, as well as mention the database details of the website on which you are going to use the login system.

<?php
require_once('vendor/autoload.php');

$google_client = new Google_Client();

$google_client->setClientId('31369693453453453450838-ptsto5435344faeu6644353454353ejfp9lgg143534542v8d750it9.apps.googleusercontent.com');

$google_client->setClientSecret('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mZs43534543543xEbfrJ07N');

$google_client->setRedirectUri('https://example.com/google/');

$google_client->addScope('email');
$google_client->addScope('profile');

session_start();

// Connect to database
$hostname = "localhost";
$username = "u336260043";
$password = "123";
$database = "u336260043";

$conn = mysqli_connect($hostname, $username, $password, $database);

?>

Create index.php files

In the index.php file, you will need to include Library, check the mail through the user details of the portal on which you are setting up the login system, then give the permission to log in, in this you have to check the database name , and which is your login table, you have to edit it.

 

<?php
date_default_timezone_set('asia/kolkata');
$date = date('d-m-Y h:i:s A',time());
$connection = mysqli_connect('localhost','u336260043','123','u336260043');

session_start();
include('config.php');


if(isset($_GET["code"])){
    $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

    if(!isset($token['error'])){
        $google_client->setAccessToken($token['access_token']);
        $_SESSION['access_token']=$token['access_token'];

        $google_service = new Google_Service_Oauth2($google_client);
        $data = $google_service->userinfo->get();
        $_SESSION['user_email_address'] =$data['email'];
        $_SESSION['user_first_name'] =$data['given_name'];
        $_SESSION['user_last_name'] =$data['family_name'];
        $_SESSION['user_image'] =$data['picture'];
        $_SESSION['verifiedEmail'] =$data['verifiedEmail'];
        $_SESSION['login_button'] =false;

  // checking if user is already exists in database
  $sql = "SELECT * FROM loginusers WHERE email_id ='{$_SESSION['user_email_address']}'";
  $results = mysqli_query($connection, $sql);
  if (mysqli_num_rows($results) > 0) {
      
      $qruiry = "UPDATE `loginusers` SET `oauthtoken` = '{$_SESSION['access_token']}', `verifiedEmail` = '{$_SESSION['verifiedEmail']}' WHERE `loginusers`.`email_id` = '{$_SESSION['user_email_address']}';";
    // user is exists
    $result = mysqli_query($connection, $qruiry);

  } else {
    echo '<script>alert("No Record Found, Please Register New Account!"); window.location.href="https://example.com/register.php";</script>';
  }
    }
}
if(isset($_SESSION['login_button'])){
   
    $login_button=$_SESSION['login_button'];
  // checking if user is already exists in database
  $sql = "SELECT * FROM loginusers WHERE email_id ='{$_SESSION['user_email_address']}'";
  $results = mysqli_query($connection, $sql);
  if (mysqli_num_rows($results) > 0) {
      
      $qruiry = "UPDATE `loginusers` SET `oauthtoken` = '{$_SESSION['access_token']}', `verifiedEmail` = '{$_SESSION['verifiedEmail']}' WHERE `loginusers`.`email_id` = '{$_SESSION['user_email_address']}';";
    // user is exists
    $result = mysqli_query($connection, $qruiry);


$usrdata = mysqli_fetch_assoc(mysqli_query($connection, "SELECT * FROM `loginusers` WHERE `email_id` = '{$_SESSION['user_email_address']}' LIMIT 1"));


$usrrsql = $connection->prepare("select count(*) from loginusers WHERE email_id = ?");
$usrrsql->execute([$_SESSION['user_email_address']]);
 $login_key =  md5(microtime().$_SERVER['REMOTE_ADDR']);

$_SESSION['login_key'] = $login_key;
$_SESSION['username'] = $usrdata['username'];

if($usrdata['status']=='approved'||$usrdata['status']=='paywait'){

$qruirys = "UPDATE `loginusers` SET `login_key` = '$login_key' WHERE `loginusers`.`email_id` = '{$_SESSION['user_email_address']}';";
    $results = mysqli_query($connection, $qruirys);

if($_REQUEST['remember']==1){
setcookie('username',$_SESSION['username'], time() + (86400 * 7), "/"); // 86400 = 1 day	
}
echo '
<script>
window.location = "https://example.com/index.php"
</script>';

}



  } else {
     $google_client->revokeToken();
session_destroy(); 
    echo '<script>alert("No Record Found, Please Register New Account!"); window.location.href="https://example.com/register.php";</script>';
  }
}else{
     $login_button = true;
     
     
}

?>


   <?php
if($login_button){
    ?>
    <script>
window.location = "<?=$google_client->createAuthUrl()?>"
</script>
    <?php
}
    ?>

Download Vendor/autoload.php

The complete source code for logging in from google or gmail is given below, you can download, and implement it in your portal.

Google sign in source code download

 

Leave a Reply

Your email address will not be published. Required fields are marked *