Login with google account using php - Google Oauth Login

In this tutorials you are going to learn how to implements Google OAuth login with your website. PHP Google OAuth API allows users to login in a website with their Google credentials. Here we'll provide the step-by-step guide to implementing login with Google account using PHP and store the user information in the MySQL database.

Our example Google login script uses the API PHP Client Library to implement Login with Google using PHP in the web application.

File Structue

Google oauth login file structure

Create Google API Console Project:

1. Go to the Google API Console.

2. Click NEW PROJECT to create a new project:
  • Enter the Project Name.
  • Under the Project Name, Creates a project ID. Project ID must be unique
  • Click on the CREATE button and the project will be created in some seconds.
3. Select Credentials under the APIs & Services section.
4. Select the OAuth consent screen tab, specify the consent screen settings.
  • In Application name field, enter the name of your Application.
  • In Support email filed, choose an email address for user support.
  • In the Authorized domains, enter domain to authenticate using OAuth.
  • Click the Save button.
5. Select the Credentials tab, click the Create credentials drop-down 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.

    Google secret Key

    Note that: This Client ID , Client secret and Authorized redirect URI need to be specified in the script at the time of Google API call.

    To create google Client Id and Client secret go through this guide toClick Here.

    Google API Client Library for PHP

    The google-api-php-client directory contains the Google OAuth Library for PHP. The composer is not required to install Google API PHP Client, it can be used without using composer. Download google-api-php-client Click Here

    config.php : API Configuration

    In the config.php file, Google API configuration constant variables are defined.

  • GOOGLE_CLIENT_ID - Specify the Google Project Client ID.
  • GOOGLE_CLIENT_SECRET - Specify the Google Project Client Secret.
  • GOOGLE_REDIRECT_URL - Specify the Callback URL.
  • config.php

    <?php
    
    // 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 coderglass.com');
    $gClient->setClientId(GOOGLE_CLIENT_ID);
    $gClient->setClientSecret(GOOGLE_CLIENT_SECRET);
    $gClient->setRedirectUri(GOOGLE_REDIRECT_URL);
    
    $google_oauthV2 = new Google_Oauth2Service($gClient);
    
    ?>
    

    index.php:

    In this file, the API authentication and authorization process are handled using PHP

    
    <?php 
    // Include configuration file 
    require_once 'config.php'; 
    session_start();
     
    if(isset($_GET['code'])){ 
        $gClient->authenticate($_GET['code']); 
        $_SESSION['token'] = $gClient->getAccessToken(); 
        header('Location: ' . filter_var(GOOGLE_REDIRECT_URL, FILTER_SANITIZE_URL)); 
    } 
     
    if(isset($_SESSION['token'])){ 
        $gClient->setAccessToken($_SESSION['token']); 
    } 
     
    if($gClient->getAccessToken()){ 
        // Get user profile data from google 
        $gProfile = $google_oauthV2->userinfo->get(); 
        
        // Getting user profile info 
    $gData = array(); 
    $gData['oauth_uid']  = !empty($gProfile['id'])?$gProfile['id']:''; 
    $gData['first_name'] = !empty($gProfile['given_name'])?$gProfile['given_name']:''; 
    $gData['last_name']  = !empty($gProfile['family_name'])?$gProfile['family_name']:''; 
    $gData['email']      = !empty($gProfile['email'])?$gProfile['email']:''; 
    $gData['gender']     = !empty($gProfile['gender'])?$gProfile['gender']:''; 
    $gData['locale']     = !empty($gProfile['locale'])?$gProfile['locale']:''; 
    $gData['picture']    = !empty($gProfile['picture'])?$gProfile['picture']:''; 
         
        $userData = $gData; 
         
        // Storing user data in the session 
        $_SESSION['userData'] = $userData; 
         
        // storing user profile data in session
        if(!empty($userData)){ 
            
    $_SESSION["upic"]= '<img width="100" src="'.$userData['picture'].'">'; 
    $_SESSION["uid"]= '<p><b>Google ID:</b> '.$userData['oauth_uid'].'</p>'; 
    $_SESSION["uname"]= '<p><b>Name:</b> '.$userData['first_name'].'</p>'; 
    $_SESSION["uemail"]= '<p><b>Email:</b> '.$userData['email'].'</p>'; 
    $_SESSION["logout"]= '<p><a href="logout.php"><b>Logout</b></a></p>'; 
           
        header("Location: home-page.php");
            
     }else{ 
     $out_error = '<h3 style="color:red">Some problem occurred, please try again.</h3>'; 
     echo $out_error;
      } 
    }else{ 
        // Get login url 
        $authUrl = $gClient->createAuthUrl(); 
         
        // google login button 
        $login_image = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'">
        <img src="images/google-sign-in-btn.png" alt=""/></a>'; 
        echo $login_image;
    } 
    ?>
    
    
    

    home-page.php

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

    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    <center>
    <?php 
    
    session_start();
    
    if(isset($_SESSION["uname"])){ 
        
     echo "<h1>You Google Details </h1>";
    
     echo   $_SESSION["upic"];
     echo   $_SESSION["uid"];
     echo   $_SESSION["uname"];
     echo   $_SESSION["uemail"];
     echo   $_SESSION["logout"];
        
    }else{
        
        header("index.php");
    }
    
    ?>
    </center>
    </body>
    </html>
    
    

    logout.php

    User can log out from their Facebook account when they click on Lougout
    • Remove token and user data from the SESSION.
    • Reset OAuth access token.
    • Destroy the entire session data.
    • Redirect the user to the homepage.
    <?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");
    ?>