How to Create Google Login with PHP

Category
Tutorial
Reading
4 mins
Views
2.4K
Posting
13 Sep 2022

As the website develops from the various features provided, we can use several libraries provided by various vendors to make it easier for website owners and website users, one of which is Google Login, maybe you've seen or even used it when visiting certain websites, with this feature This Google Login will help the user to register quickly. If you are looking for how to make a website with Google login, you are in the right article, because today we will give a simple tutorial on how to use Google Login with PHP.

Before proceeding to the point, you need to do a few things first, namely create a credential token or API Key from Google to integrate Google servers with your website, this is done to ensure whether the user data request is indeed correct from your website, namely by matching the token from the API. Key that will be used later.

 

How to Create Google Login With PHP

 

 

1. Generating Credentials/Google API Key

  • The first step is to enter the https://console.cloud.google.com/apis/dashboard.
  • Select select project then select create a new project in the upper right corner.
  • Please fill in the project name and then select the create button.
  • Select the library in the sidebar, then search for Google+ API, then enable it.
  • After the library has been created, select create credentials then select OAuth Client ID, select web application, fill in the app name and authorized redirect URIs, in the authorized redirect URIs section, fill in the Endpoint URL. which will process the data returned by Google, here we fill in http://localhost/google_login which is the index section of the project created.
  • After the form filling process is complete, a modal will appear which will display the client id and client secret, copy the two tokens into notepad.
  • The important parts needed to configure in the config.php section later are the client id, client secret and redirect URI.

 

2. Installing the Google Client library

After the process of getting the client id and client secret has been successful, the next step is to install the libraries we need into our project, here we will install the Google Client. Create a new folder for our Google login project, open a text editor such as VScode, import the project folder that we created earlier, after the project folder has been entered into VScode, it's time to install the library from the google client, open a terminal in VS code, then enter the command in the terminal:

composer require google/apiclient

Wait until the installation process is complete after that create new files named index.php, config.php, and logout.php, roughly the structure of the contents of the folder is like this:

Project/
├── vendor/
├── composer.json 
├── composer.lock 
├── index.php 
├── config.php 
└── logout.php

To display the button from google login, we create a file called index.php, in this file later we will display the button from Google login to redirect to the Google OAuth modal, and all user data if it has been successfully verified will be displayed on this page, the config file .php is used to save all credentials such as client id, client secret and redirect uri and logout to clear all sessions and reset access token from google server.

 

3. Create an index.php file

After knowing all the functions of each required file, the first thing to do is display the Google login button which will be redirected to the Google OAuth modal, you can fill in the index.php file as below:

<?php

require_once 'config.php';

if (!empty($_GET['code']))
{
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token['access_token']);

    $google_oauth = new Google_Service_Oauth2($client);
    $google_account_info = $google_oauth->userinfo->get();

    $userdata = [];
    $userdata['google_id'] = $google_account_info->id;
    $userdata['email'] = $google_account_info->email;
    $userdata['name'] = $google_account_info->name;
    $userdata['picture'] = $google_account_info->picture;
    $userdata['locale'] = $google_account_info->locale;
    $userdata['gender'] = $google_account_info->gender;
    $userdata['oauth_provider'] = 'google';
    $_SESSION['userData'] = $userdata;
    $_SESSION['token'] = $token['access_token'];

    header("Location: index.php");
}

$authUrl = $client->createAuthUrl();
$output = '<a href="' . filter_var($authUrl, FILTER_SANITIZE_URL) . '"><img src="images/google-sign-in-btn.png" alt=""/>Sign in with google</a>'; ?>

<div class="container">
    <?php
    $output = '';
    if(!empty($_SESSION['userData']))
    {
        $userdata = $_SESSION['userData'];
        $output = '<h2>Google Account Details</h2>';
        $output .= '<div class="ac-data">';
        $output .= '<img src="' . $userdata['picture'] . '">';
        $output .= '<p><b>Google ID:</b> ' . $userdata['google_id'] . '</p>';
        $output .= '<p><b>Name:</b> ' . $userdata['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> ' . $userdata['oauth_provider'] . '</p>';
        $output .= '<p>Logout from <a href="logout.php">Logout</a></p>';
        $output .= '</div>';
    } ?>

    <?php echo $output; ?>
</div>

You can also modify all of these files to make it more interesting, here we give a basic example that focuses on the Google login function itself.

 

4. Configuring the config.php file

After the index.php file has been filled in completely, the next step is to create a config.php file, which functions to store all parts of the credentials of your application such as client id, client secret and redirect uri, for each part you can adjust it. The contents of the config.php file are:

<?php

require_once 'vendor/autoload.php';

use Google\Client;

define('GOOGLE_CLIENT_ID', 'CLIENT-ID');
define('GOOGLE_CLIENT_SECRET', 'CLIENT-SECRET');
define('GOOGLE_REDIRECT_URL', 'AUTHORIZED-REDIRECT-URI');

if(!session_id())
{
    session_start();
}

$client = new Client();
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URL);
$client->addScope("email");
$client->addScope("profile");

When finished, you can click save and continue to the last part, namely the logout feature.

 

5. Logout

In the last section, this file will reset the entire session and access token obtained from the Google server, you can fill in the logout.php file as below:

<?php

// Import file config
require_once 'config.php';

// Reset access token
$client->revokeToken($_SESSION['token']);

// Remove token & userdata
unset($_SESSION['token']);
unset($_SESSION['userData']);

// destroy session
session_destroy();

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

And finally the login system using Google login has been completed perfectly, actually the Google login system is quite simple, we as clients who use the library from Google, request access to Google to get info from the user when registering, the difference that stands out compared to user registration is manual is the user does not need to input data such as name, email, password when using your application, this will certainly make it easier for users when they want to create an account in your application.

You can also combine it with a database, so when the user has finished logging in using Google login, all data obtained from Google's servers can be stored in the database. And when the user logs back into your application, all data is already in the database and the function of this Google login is only to match emails, and update some other elements such as avatars.

 

Closing

Google login is an alternative that you can use to register and login to the user to make it easier, and its use is quite easy because there are already libraries provided, to integrate this Google login you can combine it with various things such as a very large database. useful for storing all user data. If you are looking for how to integrate Google login with your website, this simple article might help you in completing the project you are working on.

Share