Login With Google Account on Website Using PHP MySQL

Login with Google Account is the most useful feature for a web application. If you provide this feature on your website. It will increase more new users to your website. Because users need not sign up or create a new account, They can directly login with their Google account credentials. So, It is the most popular feature and most website owners use it.

If you are searching for a login with a google account using PHP, You are reading the right tutorials. This tutorial will be helpful to you. It has the best steps & a simple script to learn you in a proper way. So,  read all the given points without skipping any one of those. Every Step contains a unique concept that helps you easily integrate it into your project.

login with google account using php mysql

How to Integrate Login With Google Account on Website Using PHP

You have to understand the following algorithm to easily create a login with a google account. Don’t worry, The following Every Point will be explained step by step in upcoming steps.

  • First of all, create a MySQL database & table
  • Connect MySQL database to PHP file
  • Include Google Client/ Oauth Library
  • Enter Google Client Id & Secret Key
  • Check user already exists in the database or not.
  • If the user had already existed, update otherwise insert his/her profile data.
  • You will create a login with a google account successfully

Read Also

Login With Facebook Using PHP

How to Create Login Using PHP

Now, You will learn to create a login with a google account through the following steps. Every step is very simple to learn & understand. So, You will easily learn it.

1. Configure Basic Requirement

Before going to the next step, you should configure the following basic things

Create the following folder structure

myproject/
   |__google-login/
   |       |_google-plus-api-client-master/
   |       |_api-setting.php
   |       |__callback.php
   |       |_login.php
   |       |_user-data.php
   |__dashboard.php
   |__database.php
   |__login-page.php
   |__logout.php
   |__style.css

 

Create codingstatus database  & connect it to PHP using the following script.

File Name – database.php

<?php

$hostname = "localhost"; // Enter your hostname
$username = "root"; // Enter your table username
$password = ""; // Enter your table password
$databasename = "codingstatus"; // Enter your Database name
// Create connection
$conn = new mysqli($hostname, $username, $password,$databasename);
// Check connection
if ($conn->connect_error) {
die("Unable to Connect database: " . $conn->connect_error);
}
?>

Create users table using the following query. You can use your table.

Table Name – users

CREATE TABLE `users` (
 `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('google','facebook','twitter','linkedin') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'google',
 `oauth_uid` varchar(50) DEFAULT NULL,
 `first_name` varchar(225) DEFAULT NULL,
 `last_name` varchar(225) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 `gender` varchar(10) DEFAULT NULL,
 `picture` varchar(255)DEFAULT NULL,
 `created` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I have inserted about 65 records in a users. You can insert it according to your project requirement.

2. Get Google Client and Oauth Library

Google Client & Oauth Library is necessary to integrate login with google account on your website. This library provides all the classes & files script to configure basic login requirements. With the help of it,  you can also fetch google user profile information from the Google database.

You need not get many files separately. you will get all the required files from the given URL. So, get it by just clicking the following URL.

Get Google Client and Oauth Library

You will be redirected to the Git website to get it, you should get the zip folder.

Once you have to get it successfully, extract its folder. copy & paste it in your google-login folder.

3. Create Google API Console Project

Google API Console Project provides you google Client Id & Secret Key. These are necessary to log in with google account. With the help of it, google allows users to get signing with their google account credentials. So, You have to create it to get google Client Id & Secret Key.

Now, Configure the following points to create Google API Console Project.

New Project

  • Click the New Project link to create a new project. Otherwise, If you have already created it, you can select an existing project from the project list.
  • You will get the default generated Project Name in the input field. If you want to change it, you will have to click the edit link then replace the existing project Name with your custom Name. But remember that Project Name must be unique.
  • Click the CREATE button. then Project will be created.

google console project

OAuth consent screen

  • Now click the OAuth consent screen link. It remains on the left side of the dashboard.
  • Select the External option of User Type and click the CREATE button.
  • Enter your Application Name in the Application name input filed. you can leave empty this field
  • Upload your Application logo through the Application logo input field. you can leave empty this field
  • Enter your Support email in the support email input field.
  • Enter your Authorized domain in the Authorized domain input field. It may be like an example.com.you can leave empty this field
  • Click the Save button to save these changes.

google project console

Credentials

  • Now Click Credentials link. It remains on the left side of the dashboard
  • Click the CREATE CREDENTIALS button. you will get a dropdown list then Click OAuth Client ID options od dropdown list.
  • Select Web Application in Application Type Option
  • Enter http://localhost in Authorized JavaScript origins input field. If your project is hosted in a live server, you have to enter a domain like https://codingstatus.com.
  • Enter http://localhost/codingstatus/googlelogin/google-login/callback.php in Authorized redirect URIs input field. If your project is hosted in  a live server, you have to enter the redirect URL like https://codingstatus.com/google-login/callback.php
  • Click the CREATE button.

google project console

Client ID and Client Secret

  • A popup box will appear with google Client ID & Client Secret. 
  • Copy Client ID & Client Secret and paste it into an api-setting.php file. It is explained in the next step. How to use it.

google project console

4. Update Google Login API

You have created a project to get google Client ID & Client Secret In the previous step. Now, update the following required values of a declared variable with your Client ID, Client Secret, redirect URL & application name

  • $googleClientID – Update its value with your created google Client ID
  • $googleClientSecret – Update its value with your created google Client Secret
  • $googleRedirect – Update its value of  base URL http://localhost/codingstatus/googlelogin/ with your base URL like https://codingstatus.com and leave the remaining part google-login/callback.php as it is. for example – https://codingstatus.com/google-login/callback.php.
  • $loginTo – Update its value with your application name
  • $dashboardPageURL – Update its value with your dashboard page URL where you want to redirect after login.

File Name: api-setting.php

 <?php

session_start();
 $dashboardPageURL='http://localhost/codingstatus/googlelogin/dashboard.php';

 // Google API configuration
 $googleClientID="590366725692-jhj08eh09iailf9c0a4ammj89pmh3udc.apps.googleusercontent.com";
 $googleClientSecret="JaippbxV2SXzvHxSycxcEoJm";
 $googleRedirectURL="http://localhost/codingstatus/googlelogin/google-login/callback.php";
 $loginTo="Login to CodingStatus.com";

 // Include Google API client library
 require_once 'google-plus-api-client-master/src/Google_Client.php';
 require_once 'google-plus-api-client-master/src/contrib/Google_Oauth2Service.php';
// Call Google API
$googleClient = new Google_Client();

$googleClient->setApplicationName($loginTo);
$googleClient->setClientId($googleClientID);
$googleClient->setClientSecret($googleClientSecret);
$googleClient->setRedirectUri($googleRedirectURL);

$googleService = new Google_Oauth2Service($googleClient);
?>

5. Create Google Login Link

To create a google Login link, You have to configure the following steps –

  • Include the api-setting.php
  • If the session is set then redirect to google login API
  • Get auth URL from createAuthUrl() and assign it to the $authURL
  • Sanitize $authURL and assign it to the $googleLoginLink

File Name: login.php

<?php

require('api-setting.php');

if(isset($_SESSION['access_token'])){ 

   header('Location: ' . filter_var($googleRedirectURL, FILTER_SANITIZE_URL)); 
   exit();
}
    $authURL = $googleClient->createAuthUrl(); 
      //google Login Button
    $googleLoginLink= filter_var($authURL, FILTER_SANITIZE_URL);
?>

You can echo in anchor tag the $googleLoginLink of google login link in any web pages where you want to create a login with a google account.

6. Fetch Google User Profile Data

Use the following script to fetch user profile data from the Google database and pass it in the custom function to insert data into your own database. this file will be called after getting login with a google account.

File Name – callback.php

 <?php

require('api-setting.php');
require('user-data.php');


if(isset($_SESSION['access_token'])){
   $googleClient->setAccessToken($_SESSION['access_token']);

}else if(isset($_GET['code'])) {
   $googleClient->authenticate($_GET['code']); 
   $_SESSION['access_token'] = $googleClient->getAccessToken(); 
    
}else{
  header('location:login.php');
  exit();
}
 
if(isset($_SESSION['access_token'])){ 


    // Get user profile data from google 
    $userInfo = $googleService->userinfo->get(); 
     
   $id= !empty($userInfo['id'])? $userInfo['id']:'';
   $firstName= !empty($userInfo['given_name'])? $userInfo['given_name']:''; 
   $lastName= !empty($userInfo['family_name'])? $userInfo['family_name']:''; 
   $email= !empty($userInfo['email'])?$userInfo['email']:''; 
   $gender= !empty($userInfo['gender'])? $userInfo['gender']:''; 
   $picture= !empty($userInfo['picture'])? $userInfo['picture']:''; 

    // Getting user profile info 
  $data = [
     'oauth_uid'  => $id,
     'first_name' => $firstName,
     'last_name'  => $lastName,
     'email'      => $email,
     'gender'     => $gender,
     'picture'    => $picture


  ];
   
    // Insert or update user data to the database 
    $data['oauth_provider'] = 'google'; 

    $userData = user_data($data,$tableName);
    // logged in user data

    $_SESSION['user_data']= $userData; 

     header('Location: ' . filter_var($dashboardPageURL, FILTER_SANITIZE_URL)); 
  
}
?>

 

7. Store User Profile Data into MySQL Database

You have to specify your database connection variable & table name where you want to insert user information.

  • $db – Update its value with your database connection variable
  • $tableName – Update its value with your table name variable

Use the following PHP Script to store google user profile information in your database. You need not change anything in the given script.

File Name: user-data.php

<?php

 // Start session
require_once('../database.php');

 $db=$conn;
 $tableName='users';

function user_data($data,$tableName){

        $existUser=exist_user($data, $tableName);
        return $existUser;
  }

  function  exist_user($data,$tableName){
       global $db;
       $existQuery="SELECT * from ".$tableName." WHERE oauth_provider='".$data['oauth_provider']."' AND oauth_uid='".$data['oauth_uid']."'";
      $existResult=$db->query($existQuery);
      if ($existResult->num_rows> 0) {
          
          update_user($data,$tableName);
      }else{
          insert_user($data, $tableName);
      }
    $fetchUserData = $existResult->fetch_assoc(); 
    return $fetchUserData;
  }

  function update_user($data,$tableName){
      
     global $db;
     $columnsValues = ''; 
     $num = 0; 
     foreach($data as $column=>$value){ 
                    
             $comma = ($num > 0)?', ':''; 
             $columnsValues.=$column." = ".$value.$comma;
             $num++; 
      } 

      $updateQuery="UPDATE".$tableName." SET ".$columnsValues." WHERE oauth_provider='".$data['oauth_provider']."' AND oauth_uid='".$data['oauth_uid']."'";
      
      $updateResult=$db->query($updateQuery);
      if($updateResult){
      return "Error: " . $updateResult . "<br>" . $db->error;
      }
  }

function insert_user($data,$tableName){
       
     global $db;

     $tableColumns = $userValues = ''; 
     $num = 0; 
     foreach($data as $column=>$value){ 
          $comma = ($num > 0)?', ':''; 
          $tableColumns .= $comma.$column; 
          $userValues  .= $comma."'".$value."'"; 
          $num++; 
      } 
    $insertQuery="INSERT INTO ".$tableName."  (".$tableColumns.")VALUES(".$userValues.")";
    $insertResult=$db->query($insertQuery);
    if($insertResult){
     return "Error: " . $insertQuery . "<br>" . $db->error;
    }

}
?>

 

8. Display Google Login Button On Web Page

To display the google login button, you have to implement the following steps –

  • Include the login.php
  • Print $googleLoginLink within the anchor tag

File Name- login-page.php

 <?php

require('google-login/login.php');
?>


<a href="" class="google-login-btn">Login with Google</a>

9. Display Google User Profile Data

You can display google user profile data on the dashboard page after getting logged in. So, you have to create a dashboard page with the following steps –

  • start session at the top of page
  • If Login session is set  then display user profile otherwise redirect to login page
  • Also, create a link to logout.

File Name- dashboard.php

<?php

session_start();

if(isset($_SESSION['access_token'])){ 
 $userData=$_SESSION['user_data'];

}else{
  header("location:login-page.php");
}
?>

<p>Oauth id -</p>
<p>Oauth Provider -</p>
<p>First Name- </p>
<p>Last Name - </p>
<p>Email - </p>
<p>Gender - </p>
<p>Picture - <img src="" width="200px" height="200px"></p>
<p><a href="logout.php">Logout</a></p>

10. Design Google Login Button

You can design a google login button with a few lines of CSS code. You can also write more css code according to your project theme.

File Name- style.css

.google-login-btn{
    background: #ea701a;
    padding: 5px 10px;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    font-size: 20px;
    font-weight: bold;
  }

11.Create google Logout

You can create a google logout button by writing PHP code according to the following steps –

  • First of all, start the sessionn.
  • Unset session of user data.
  • After that, destroy the created session.
  • At last, redirect to the login page.

File Name: logout.php

<?php

 session_start();
 unset($_SESSION['user_data']);
 session_destroy();
 header("location:login-page.php");
?>

My Suggestion

I hope you like this tutorial. Even it is useful for you. So, Don’t forget to share with friends those who want to learn it.

If you have any queries, you can ask me through the below comment box. I will also share more coding tutorials. So you should continue to visit my blog for becoming an expert in the coding field.

Categories PHP

Leave a Comment