How to Add Google OAuth Login in Website with PHP

If you are running a website having a registration page, you may want to add a Google OAuth login for the user’s convenience. Google sign-in makes registration flow easy for both users and site owners.

Your users can use their Google account to sign up on your website. They don’t need to fill out your registration form, activate their account through email, etc.

In this article, we study how to add the Google OAuth login to your website using PHP.

Get Your Google API Credentials

To get started with Google login API, you first need to create a console project on Google and get your credentials. Below are the steps you should perform to create the Google project.

  • Go to Google Developer Console.
  • Click on the drop-down and create a new project by clicking on the (+) sign. Alternatively, you can select the existing project also.
  • Select Credentials from the sidebar under APIs & Services.
  • Under the Credentials tab, click on the Create credentials drop-down and select OAuth client id.
  • Select the Web application from the Application type. In the Authorized redirect URLs enter the URL YOUR_DOMAIN_URL/index.php.
  • Once you save it, you will get the dialog box along with your Client ID and Client secret. Copy these keys which we will require in the next steps.

You may notice the redirect URL set to the index.php file path. This is the file where I will write the code for callback handling. Users are free to use any other file for this purpose.

Installation of HybridAuth Library

HybridAuth is an open-source social sign-on PHP library. Using this library, we can add a social login for one or multiple providers like Google, Facebook, Twitter, etc. This package provides the simplest way for integrating social login into the website.

Hybridauth Social Login PHP Library

Let’s install the HybridAuth library using a composer. Create a composer.json file in the project root folder and add the below code in it.

{
    "require" : {
        "hybridauth/hybridauth" : "~3.0"
    }
}

Next, open the terminal in your project root directory and run the command:

composer install

Create the config.php file and add the code below in it to configure the Google OAuth login.

<?php
require_once 'vendor/autoload.php';
 
$config = [
    'callback' => 'YOUR_DOMAIN_URL/index.php',
    'keys'     => [
                    'id' => 'YOUR_CLIENT_ID',
                    'secret' => 'YOUR_CLIENT_SECRET'
                ],
    'scope'    => 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
    'authorize_url_parameters' => [
            'approval_prompt' => 'force', // to pass only when you need to acquire a new refresh token.
            'access_type' => 'offline'
    ]
];
 
$adapter = new Hybridauth\Provider\Google( $config );

Make sure to replace the placeholders with their actual values. In the above code, I passed YOUR_DOMAIN_URL/index.php as a callback URL. Adjust this path as per your requirement.

Add Google OAuth Login

We are set with the configurations and good to go ahead. Create 2 files index.php and logout.php in your project root directory.

The index.php would be responsible for initiating Google login, handling the OAuth flow, and getting the logged-in user’s profile.

index.php

<?php
require_once 'config.php';
 
try {
    $adapter->authenticate();
    $userProfile = $adapter->getUserProfile();
    print_r($userProfile);
    echo '<a href="logout.php">Logout</a>';
}
catch( Exception $e ){
    echo $e->getMessage() ;
}

When you run index.php in the browser, the code first checks whether the user is authenticated with ‘Google’ or not. If not, it redirects to the Google sign-in page. The user has to log in with their Google account. On successful authentication, the user will redirect to the index.php file. On the same page, we are getting a user profile using the method getUserProfile().

In the logout.php file, we just need to disconnect the Google adapter which will log out the user.

logout.php

<?php
require_once 'config.php';
 
try {
    if ($adapter->isConnected()) {
        $adapter->disconnect();
        echo 'Logged out the user';
        echo '<p><a href="index.php">Login</a></p>';
    }
}
catch( Exception $e ){
    echo $e->getMessage() ;
}

I hope you may learn about Google OAuth Login on a website with PHP. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

2 thoughts on “How to Add Google OAuth Login in Website with PHP

  1. i’ve followed the article but i get PHP Fatal error: Uncaught Error: Class ‘HybridauthProviderGoogle’ not found in when i try to use the adapter

Leave a Reply

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