Login with Google OAuth using PHP

 Hi There,

In this tutorial you will learn How to Implement Google Login API in PHP.

 Create Google API Console Project
1.Go to Google Console https://console.developers.google.com/

2.Create New Project to a new project.

  • Enter your project name
  • Under the project name, creates a project ID. It must be unique Id.
  • Then click on the create button and your project will be created.


3.Select Credentials under the apis & service section
Select Credentials and click on create credentials 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 Client ID and Client secret. This Client ID and Client secret allow you to access the Google APIs.



4.Select Oauth Consent and specify below.
In App name field, enter the name of your application
enter email in the support email field.
upload your app logo
add your domain into app domain, application home page, application privacy policy

Enter your developer contact information







Folder Structure:


 

 

 

 

 

 

 

 


Install google api client library using below command

 
composer require google/apiclient:"^2.0"
 


Create config.php and and copy/paste below code in config.php

    <?php

    //config.php

    //Include Google Client Library for PHP autoload file
    require_once 'vendor/autoload.php';

    //Make object of Google API Client for call Google API
    $google_client = new Google_Client();

    //Set the OAuth 2.0 Client ID
    $google_client->setClientId('<place client id>');

    //Set the OAuth 2.0 Client Secret key
    $google_client->setClientSecret('<place your client secret key>');

    //Set the OAuth 2.0 Redirect URI
    $google_client->setRedirectUri('http://localhost/google-login-php/index.php');

    //
    $google_client->addScope('email');

    $google_client->addScope('profile');

    //start session on web page
    session_start();

    ?>


 Create index.php and copy/paste below code:
In this file, the API authentication and authorization process are handled using PHP 

 


    <?php

    //index.php

    //Include Configuration File
    include('config.php');

    $login_button = '';

    //This $_GET["code"] variable value received after user has login into their Google Account redirct to PHP script then this variable value has been received
    if(isset($_GET["code"]))
    {
    //It will Attempt to exchange a code for an valid authentication token.
    $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

    //This condition will check there is any error occur during geting authentication token. If there is no any error occur then it will execute if block of code/
    if(!isset($token['error']))
    {
    //Set the access token used for requests
    $google_client->setAccessToken($token['access_token']);

    //Store "access_token" value in $_SESSION variable for future use.
    $_SESSION['access_token'] = $token['access_token'];

    //Create Object of Google Service OAuth 2 class
    $google_service = new Google_Service_Oauth2($google_client);

    //Get user profile data from google
    $data = $google_service->userinfo->get();

    //Below you can find Get profile data and store into $_SESSION variable
    if(!empty($data['given_name']))
    {
    $_SESSION['user_first_name'] = $data['given_name'];
    }

    if(!empty($data['family_name']))
    {
    $_SESSION['user_last_name'] = $data['family_name'];
    }

    if(!empty($data['email']))
    {
    $_SESSION['user_email_address'] = $data['email'];
    }

    if(!empty($data['gender']))
    {
    $_SESSION['user_gender'] = $data['gender'];
    }

    if(!empty($data['picture']))
    {
    $_SESSION['user_image'] = $data['picture'];
    }
    }
    }

    //This is for check user has login into system by using Google account, if User not login into system then it will execute if block of code and make code for display Login link for Login using Google account.
    if(!isset($_SESSION['access_token']))
    {
    //Create a URL to obtain user authorization
    $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="image/google.png" /></a>';
    }

    ?>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>PHP Login using Google Account</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
    
    </head>
    <body>
    <div class="container">
    <br />
    <h2 align="center">PHP Login using Google Account</h2>
    <br />
    <div class="panel panel-default">
    <?php
    if($login_button == '')
    {
        echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
        echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
        echo '<h3><b>Name :</b> '.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
        echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
        echo '<h3><a href="logout.php">Logout</h3></div>';
    }
    else
    {
        echo '<div align="center">'.$login_button . '</div>';
    }
    ?>
    </div>
    </div>
    </body>
    </html>


 We have stored the google information in Session. The Google account information (name, email, profile picture, and profile link) is displayed on the index.php

 Create a logout.php and copy/paste below code in logout.php

     
    <?php

    //logout.php

    include('config.php');

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

    //Destroy entire session data.
    session_destroy();

    //redirect page to index.php
    header('location:index.php');

    ?>


 Download Source code

Comments