Login with Google Account using PHP

Make a Google API Console Project

Google API provides you with an easy and effective way to unified the login system of the website. The Google Login API allows the user to sign in to the site using their Google account without sign up on that website. Google login system helps to increase customers on your website. Therefore, in the era of the internet, almost all users have a Google account. So, they can log in with their Google account without registering on your website.

The web developers can quickly implement the registration and login system in a web application using PHP and Google OAuth 2.0. In this tutorial, we’ll explain to you how to unify the user login system with Google authentication using Google API PHP library. 

Here we will provide a step-by-step guide. To implement login with Google account using PHP and store user information in MySQL database, For instance, uses the API PHP client library to get login with Google using PHP in a Google login script web application. Before proceeding to integrate login with Google using PHP and MySQL, let us first have a look at the file structure.

google_login_php/

google_login_php/
├── config.php
├── index.php
├── logout.php
├── User.class.php
├── google-api-php-client/
├── css/
│   └── style.css
└── images/
    └── google-sign-in-btn.png

Make a Google API Console Project

  1. Go to the Google API Console.
  2. Choose an existing project from the above projects list, or click NEW PROJECT to create a new project: 
    1. Enter the Project Name.
    2. Under the project name, you will see that the Google API console itself creates a project ID. Alternatively, you can change this project ID by edit link. But worldwide project IDs must be unique.
    3. Click on CREATE, and the project will be created just in a while 
  3. In the navigation panel on the left side, choose Credentials under the APIs & Services section.
  4. Click on the OAuth consent screen tab, specify consent screen settings.
    1. In the Application name field, enter the name of your Application.
    2. In the Support email filed, select an email address for user support.
    3. Specify the domains which will be allowed to authenticate using OAuth in the Authorized domains
    4. Now click on the Save 
  5. Firstly, select Credentials. Secondly, click the Create credentials drop-down, and lastly, select OAuth client ID.
    1. Select Web application in the Application type
    2. Now enter the redirect URL in the Authorized redirect URIs field
    3. Click on the Create

Soon after performing the above steps, you will see a dialogue box containing OAuth client details. Note the Client ID and Client Secret. This client ID and client secret will allow you to reach the Google API.

Make a Google API Console Project

Note: Specify the client ID and client secret in the script at the time of the Google API call. Besides, the authorized redirect URI must match the redirect URL specified in the script.

Create Database Table

There is a great need to create a table in the database to store user account information from Google. The following SQL creates a user table with some primary fields in the MySQL database to hold Google profile information.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(25) 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,
 `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

User Class (User.class.php)

The  google-api-php-client/ / directory contains the Google OAuth library for PHP. Therefore, the Composer does not need to install the Google API PHP client and can be used without using the Composer. All the necessary files of the Google API Library are combined in the Google Login PHP source code.

The User class handles the database related operations ( insert, connect, and update) using PHP and MySQL. It will help you to connect to the database and insert/update Google account data in the user’s table.

  1. construct() – Connect to the MySQL database.
  2. checkUser() – Insert 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;
        
        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($userData = array()){
            if(!empty($userData)){
                // Check whether user data already exists in the database
                $checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
                $checkResult = $this->db->query($checkQuery);
                if($checkResult->num_rows > 0){
                    // Update user data if already exists
                    $query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
                    $update = $this->db->query($query);
                }else{
                    // Insert user data in the database
                    $query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = NOW(), modified = NOW()";
                    $insert = $this->db->query($query);
                }
                
                // Get user data from the database
                $result = $this->db->query($checkQuery);
                $userData = $result->fetch_assoc();
            }
            
            // Return user data
            return $userData;
        }
    }

     

Site Settings and API Configuration (config.php)

Constant variables are defined in the config.php file, database settings, and Google API configuration.

  1. DB_HOST – For the database host.
  2. DB_USERNAME – For the database username.
  3. DB_PASSWORD – For the database password.
  4. DB_NAME – For the database name.
  5. DB_USER_TBL – For the table name.

Google API constants:

  1. GOOGLE_CLIENT_ID – It Specifies the Google Project Client ID.
  2. GOOGLE_CLIENT_SECRET – It Specifies the Google Project Client Secret.
  3. GOOGLE_REDIRECT_URL – It Specifies the Callback URL.

Call Google API:

To attach with Google API and to work with OAuth client, you need to use the Google Client library.

<?php
/*
 * Basic Site Settings and API Configuration
 */

// 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: You’ll get the Client ID and Client Secret on the Google API Manager page of the API Console project.

Login & Get Google Account Data (index.php)

Control the API authentication and authorization process by using PHP.

  1. In the beginning, Generate the login URL for authentication, and the user will see the Google Sign-in button.
  2. The following things happen if the user authenticates with their Google account

Logout (logout.php)

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

<?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");
?>

Conclusion

Firstly, We’ve tried to make the Google Login integration process faster and easier. Secondly, the instance code integrates Google Login with the Google API Client for PHP. Besides, you don’t need to add API Client Library files separately. And Finally, our source code contains all the required data with the OAuth client for PHP.

Also, read our previous blog- Login with Google Account using JavaScript

Exit mobile version