How to Add Google OAuth Login in Website with PHP

If you are running a website where a user can register then you may want to add Google OAuth login feature. Google sign in for websites adds an easy registration process for users. Your users can use their Google account for sign up to your website. They don’t need to fill your registration form, activate their account through email, etc.

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

Get Your Credentials

To get started with Google login API, you first need to create a 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 (+) sign. Alternately, you can select the existing project also.
  • Select your project and click on ‘ENABLE APIS AND SERVICES’. In the search box type ‘Google+’ and select the Google+ API. Enable it.
  • Again come to your project dashboard and select Credentials from the sidebar.
  • Under Credentials tab, click on the Create credentials drop-down and select OAuth client id.
  • Select the Web application from 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 next steps.

You may notice the redirect URL we set in the application. In this tutorial, we will handle callback code in the index.php. 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.

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 code below in it to configure the Google 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 the actual values. In the above code we passed YOUR_DOMAIN_URL/index.php as a callback value. Adjust this path as per your requirement.

Add Google OAuth Login

We all set with our configurations and good to go ahead. So, let’s create files index.php and logout.php in your project root directory.

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() ;
}

Now when you run index.php in the browser, our code first checks whether the user is authenticated with ‘Google’ or not. If not, then it redirects to the Google sign-in page. The user has to log in with their Google account and then it will redirect to the index.php again. Once user comes to login page we are getting user profile by using the method getUserProfile().

In the logout.php file we just need to disconnect the Google adapter.

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() ;
}

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

Related Articles

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

1 thought on “How to Add Google OAuth Login in Website with PHP

Leave a Reply

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