Login with Google Account using PHP

Google OAuth API provides an easy and powerful way to integrate the login system on the website. Google Login API allows the user to sign in to the website using their Google account without signing up on that website. The Google login system definitely helps to increase the number of subscribers on your website. Because nowadays almost all users have a Google account and they can log in with their Google account without registration on your website.

Web developers can easily implement the login and registration system in the web application using Google OAuth 2.0 and PHP. In this tutorial, we’ll show how to integrate user login system with Google authentication using Google API PHP library. Here we’ll provide a step-by-step guide to implementing login with Google account using PHP and storing the user information in the MySQL database. Our example Google login script uses the API PHP Client Library to implement Login with Google using PHP in the web application.

Before getting started to integrate Login with Google using PHP and MySQL, take a look at the file structure.

google_login_with_php/
├── config.php
├── index.php
├── logout.php
├── User.class.php
├── google-api-php-client/
└── css/
    └── style.css

Create Google API Console Project

  1. Go to the Google API Console.
  2. 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.
  3. Select OAuth consent screen from the left side navigation panel, and specify the consent screen settings.
    • Set User Type to External, and CREATE.
    • Provide app information, SAVE AND CONTINUE.
    • You can skip the Scopes settings, SAVE AND CONTINUE.
    • In the Test users setting, add users with gmail addresses.
      – While the publishing status is set to “Testing”, only test users are able to access this app.
    • SAVE AND CONTINUE
  4. Select the Credentials from the left side navigation panel, 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.

google-api-developer-cloud-console-project-app-create-client-id-secret-codexworld

Note that: This Client ID and Client secret need to be specified in the script at the time of Google API call. Also, the Authorized redirect URI needs to be matched with the redirect URL that specified in the script.

Do you want a detailed guide on Google Application creation? Go through this guide to create Google API Console Project and get Client ID & Client secret.

Create Database Table

A table is required in the database to store the user account information from Google. 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',
 `oauth_uid` 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,
 `gender` 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;

Google API Client Library for PHP

The google-api-php-client directory contains the Google OAuth Library for PHP. The composer is not required to install Google API PHP Client, it can be used without using composer. You don’t need to download it separately, all the required files of the Google API Library are included in our Google Login PHP source code.

User Class (User.class.php)

The User class handles the database related operations (connect, insert, and update) using PHP and MySQL. It helps to connect to the database and insert/update Google account data in the users table.

  • __construct() – Connect to the MySQL database.
  • checkUser() – Insert or update the user data based on the OAuth provider and ID. Returns the account data of a specific user as an array.
<?php 
/*
 * User Class
 * This class is used for database related (connect, insert, and update) operations
 * @author    CodexWorld.com
 * @url        http://www.codexworld.com
 * @license    http://www.codexworld.com/license
 */

class User {
    private 
$dbHost     DB_HOST;
    private 
$dbUsername DB_USERNAME;
    private 
$dbPassword DB_PASSWORD;
    private 
$dbName     DB_NAME;
    private 
$userTbl    DB_USER_TBL;
    private 
$db;
    
    function 
__construct(){
        if(!isset(
$this->db)){
            
// Connect to the database
            
$conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
            if(
$conn->connect_error){
                die(
"Failed to connect with MySQL: " $conn->connect_error);
            }else{
                
$this->db $conn;
            }
        }
    }
    
    function 
checkUser($data = array()){
        if(!empty(
$data)){
            
// Check whether the user already exists in the database
            
$checkQuery "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
            
$checkResult $this->db->query($checkQuery);
            
            
// Add modified time to the data array
            
if(!array_key_exists('modified',$data)){
                
$data['modified'] = date("Y-m-d H:i:s");
            }
            
            if(
$checkResult->num_rows 0){
                
// Prepare column and value format
                
$colvalSet '';
                
$i 0;
                foreach(
$data as $key=>$val){
                    
$pre = ($i 0)?', ':'';
                    
$colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
                    
$i++;
                }
                
$whereSql " WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
                
                
// Update user data in the database
                
$query "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql;
                
$update $this->db->query($query);
            }else{
                
// Add created time to the data array
                
if(!array_key_exists('created',$data)){
                    
$data['created'] = date("Y-m-d H:i:s");
                }
                
                
// Prepare column and value format
                
$columns $values '';
                
$i 0;
                foreach(
$data as $key=>$val){
                    
$pre = ($i 0)?', ':'';
                    
$columns .= $pre.$key;
                    
$values  .= $pre."'".$this->db->real_escape_string($val)."'";
                    
$i++;
                }
                
                
// Insert user data in the database
                
$query "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
                
$insert $this->db->query($query);
            }
            
            
// Get user data from the database
            
$result $this->db->query($checkQuery);
            
$userData $result->fetch_assoc();
        }
        
        
// Return user data
        
return !empty($userData)?$userData:false;
    }
}

?>

Site Settings and API Configuration (config.php)

In the config.php file, database settings and Google API configuration constant variables are defined.
Database constants:

  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.
  • DB_USER_TBL – Specify the table name where the user’s account data will be stored.

Google API constants:

  • GOOGLE_CLIENT_ID – Specify the Google Project Client ID.
  • GOOGLE_CLIENT_SECRET – Specify the Google Project Client Secret.
  • GOOGLE_REDIRECT_URL – Specify the Callback URL.

Call Google API:
The Google Client library is used to connect with Google API and working with OAuth client.

<?php

// Database configuration
define('DB_HOST''MySQL_Database_Host');
define('DB_USERNAME''MySQL_Database_Username');
define('DB_PASSWORD''MySQL_Database_Password');
define('DB_NAME''MySQL_Database_Name');
define('DB_USER_TBL''users');

// Google API configuration
define('GOOGLE_CLIENT_ID''Insert_Google_Client_ID');
define('GOOGLE_CLIENT_SECRET''Insert_Google_Client_Secret');
define('GOOGLE_REDIRECT_URL''Callback_URL');

// Start session
if(!session_id()){
    session_start();
}

// Include Google API client library
require_once 'google-api-php-client/Google_Client.php';
require_once 'google-api-php-client/contrib/Google_Oauth2Service.php';

// Call Google API
$gClient = new Google_Client();
$gClient->setApplicationName('Login to CodexWorld.com');
$gClient->setClientId(GOOGLE_CLIENT_ID);
$gClient->setClientSecret(GOOGLE_CLIENT_SECRET);
$gClient->setRedirectUri(GOOGLE_REDIRECT_URL);

$google_oauthV2 = new Google_Oauth2Service($gClient);

Note that: You’ll find the Client ID and Client Secret on the Google API Manager page of the API Console project.

Login & Get Google Account Data (index.php)

In this file, the API authentication and authorization process are handled using PHP.

  • Initially, The login URL is generated for authentication and Google Sign-in button is shown to the user.
  • If the user authenticates with their Google account, the following happens:
    • The profile information is retrieved from the Google account.
    • The account data is inserted into the database using checkUser() function of User class.
    • The user’s account info is stored in the SESSION.
    • The Google account information (name, email, gender, locale, profile picture, and profile link) is displayed on the webpage.
<?php 
// Include configuration file
require_once 'config.php';

// Include User library file
require_once 'User.class.php';

if(isset(
$_GET['code'])){
    
$gClient->authenticate($_GET['code']);
    
$_SESSION['token'] = $gClient->getAccessToken();
    
header('Location: ' filter_var(GOOGLE_REDIRECT_URLFILTER_SANITIZE_URL));
}

if(isset(
$_SESSION['token'])){
    
$gClient->setAccessToken($_SESSION['token']);
}

if(
$gClient->getAccessToken()){
    
// Get user profile data from google
    
$gpUserProfile $google_oauthV2->userinfo->get();
    
    
// Initialize User class
    
$user = new User();
    
    
// Getting user profile info
    
$gpUserData = array();
    
$gpUserData['oauth_uid']  = !empty($gpUserProfile['id'])?$gpUserProfile['id']:'';
    
$gpUserData['first_name'] = !empty($gpUserProfile['given_name'])?$gpUserProfile['given_name']:'';
    
$gpUserData['last_name']  = !empty($gpUserProfile['family_name'])?$gpUserProfile['family_name']:'';
    
$gpUserData['email']       = !empty($gpUserProfile['email'])?$gpUserProfile['email']:'';
    
$gpUserData['gender']       = !empty($gpUserProfile['gender'])?$gpUserProfile['gender']:'';
    
$gpUserData['locale']       = !empty($gpUserProfile['locale'])?$gpUserProfile['locale']:'';
    
$gpUserData['picture']       = !empty($gpUserProfile['picture'])?$gpUserProfile['picture']:'';
    
    
// Insert or update user data to the database
    
$gpUserData['oauth_provider'] = 'google';
    
$userData $user->checkUser($gpUserData);
    
    
// Storing user data in the session
    
$_SESSION['userData'] = $userData;
    
    
// Render user profile data
    
if(!empty($userData)){
        
$output     '<h2>Google Account Details</h2>';
        
$output .= '<div class="ac-data">';
        
$output .= '<img src="'.$userData['picture'].'">';
        
$output .= '<p><b>Google ID:</b> '.$userData['oauth_uid'].'</p>';
        
$output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';
        
$output .= '<p><b>Email:</b> '.$userData['email'].'</p>';
        
$output .= '<p><b>Gender:</b> '.$userData['gender'].'</p>';
        
$output .= '<p><b>Locale:</b> '.$userData['locale'].'</p>';
        
$output .= '<p><b>Logged in with:</b> Google Account</p>';
        
$output .= '<p>Logout from <a href="logout.php">Google</a></p>';
        
$output .= '</div>';
    }else{
        
$output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }
}else{
    
// Get login url
    
$authUrl $gClient->createAuthUrl();
    
    
// Render google login button
    
$output '<a href="'.filter_var($authUrlFILTER_SANITIZE_URL).'" class="login-btn">Sign in with Google</a>';
}
?> <div class="container"> <!-- Display login button / Google profile information --> <?php echo $output?> </div>

Logout (logout.php)

When the user wishes to log out from their Google account, the logout.php file is loaded.

  • Remove token and user data from the SESSION.
  • Reset OAuth access token.
  • Destroy the entire session data.
  • Redirect the user to the homepage.
<?php 

// Include configuration file
require_once 'config.php';

// Remove token and user data from the session
unset($_SESSION['token']);
unset(
$_SESSION['userData']);

// Reset OAuth access token
$gClient->revokeToken();

// Destroy entire session data
session_destroy();

// Redirect to homepage
header("Location: index.php");
exit();

?>

Publish Google API Console Project

Once the Google login integration is completed and the authentication process is working properly, you need to make the Google API Console Project public.

  • While the publishing status is set to Testing, only specified test users are able to access this app.
  • While the publishing status is set to Public, this app is available for all Google users.

You need to submit the application for verification to make the Google Cloud Console project public.

  • Navigate to the OAuth consent screen and click the PUBLISH APP button.
google-api-developer-cloud-console-project-app-publish-public-codexworld

Conclusion

We’ve tried to make the Google Login integration process quicker and easier. The example code integrates Google Login with the Google API Client for PHP. Also, you don’t need to add API Client Library files separately, our source code contains all the required files with the OAuth client for PHP. If you want to provide a user-friendly login interface, integrate Google Login without page refresh using JavaScript API – Login with Google Account using JavaScript

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

104 Comments

  1. Allwin Said...
  2. Jonathan Joles Said...
  3. Shailesh Said...
    • CodexWorld Said...
  4. Dipayan Said...
  5. Andrew Ruff Said...
    • CodexWorld Said...
  6. Vinícius Said...
  7. Vinícius Vicente Alves Terçariol Said...
    • CodexWorld Said...
  8. Mario A Dorantes Said...
    • CodexWorld Said...
  9. ElChY Said...
  10. Ayaz Said...
  11. QuickHaraj Said...
  12. Ekta Said...
  13. Ahmed Said...
  14. Bindeshwar Kushwaha Said...
  15. Jean Delcapitaine Said...
  16. Mysafehouse Said...
  17. ClemBoy57 Said...
    • CodexWorld Said...
  18. Tehmoor Khan Said...
  19. Deepak Bodkhe Said...
  20. Thiru Said...
  21. Manju Said...
    • CodexWorld Said...
  22. Ravi Said...
  23. Dibyajyoti Das Said...
  24. Sumit Said...
  25. Auda Said...
    • CodexWorld Said...
  26. Sudip Dey Said...
  27. Merit Said...
  28. BuMoRi Said...
  29. Banothu Ramesh Naik Said...
  30. Pratibha Said...
  31. Demank Said...
  32. Axl Said...
  33. Haresh Jambucha Said...
  34. Zubair Said...
  35. Bill Said...
  36. Vinay Said...
  37. Ebenezer Said...
  38. Abhay Suresh Bhosale Said...
  39. Tom Isenbaert Said...
  40. Pritesh Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up