Login With Google using PHP

Login With Google using PHP

  • Sharad Jaiswal
  • PHP Tutorials
  • 18th Nov, 2019

Hello friends, in this PHP tutorial I am going to show how to Login with Google in PHP.

As we all know that every web application is having both login as well as sign up form where we register first and then can get access to the services but sometimes it seems time-consuming as irritating.

Today most of us have Google Account, hence if web application or website allows login through the Google Account, then obviously it would be helpful for the user ease and better user base.

In order to integrate Google Auth Login API, we need Google API which allows users to login with their existing Google Accounts to any website.

Below are the steps to integrate Google Login API in PHP Website.

Getting Google API Credentials

Our first requirement is "Google API Keys" and for this, we must have a Google Account. So after login into our Google Account, we have to follow the steps mentioned below:

  • Visit the URL 'https://console.developers.google.com/'
  • Then You will notice a welcome pop-up, select your country, check the terms of services and agree and continue.
  • Click on Create link to create a new project.

    Login with Google in PHP Step1

  • After filling up the project name click on create.

    Creating Google API Keys

  • Now Click on Google API Logo to get back to the home page.
  • Select Project From Project Select Box after selection you will see a pop-up with a listing of many projects where you can choose your project.

    Select Project

    Select project google API

  • Now Click on OAuth Consent Screen on the left sidebar, once you click on it you will one page in which you have to feed the application name and then click on the save button.

    Create Application google app

  • After Saving, it will redirect to another page, where you have to click on the ‘Create Credentials’ button. You have to select the OAuth client ID from the drop-down menu that you notice there.

    Oauth client

    oauth client select

  • When you click on OAuth Client ID it will redirect you to a page in which you will notice different types of applications. As we are looking for a web application so we will choose the web application option.
  • When we choose this option a form will appear, in which we need to define Name and Authorized redirect URLs and then click on the CREATE button.

    Select Application Type

  • After we click on create we get our client ID and client secret key. Copy both of these for further use.
  • Now we would use command prompt for downloading Google API client library for PHP. On windows open cmd and type below command to install Google API client library.
    composer  require google/apiclient:"ᶺ2.0"
     Running above command will download the Google API client library.
  • Set Client Id and Client scret in config.php file.

Setting configuration in PHP Files

  • config.php file

    	//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('id goes here');
    	//Set the OAuth 2.0 Client Secret key
    	$google_client->setClientSecret('Your client secret');
    	//Set the OAuth 2.0 Redirect URI
    	//start session on web page
  • Index.php file

    //Include Configuration File
    $login_button = '';
    //This $_GET["code"] variable value received after user has login into their Google Account redirect to PHP script then this variable value has been received
     //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/
      //Set the access token used for requests
      //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
       $_SESSION['user_first_name'] = $data['given_name'];
       $_SESSION['user_last_name'] = $data['family_name'];
       $_SESSION['user_email_address'] = $data['email'];
       $_SESSION['user_gender'] = $data['gender'];
       $_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.
     //Create a URL to obtain user authorization
     $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="sign-in-with-google.png" /></a>';
      <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" />
      <div class="container">
       <br />
       <h2 align="center">PHP Login using Google Account</h2>
       <br />
       <div class="panel panel-default">
       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>';
        echo '<div align="center">'.$login_button . '</div>';
  • logout.php

    //Reset OAuth access token
    //Destroy entire session data.
    //redirect page to index.php

About Author :

  • Author of

    Sharad Jaiswal

    My name is Sharad Jaiswal, and I am the founder of Conax web Solutions. My tech stacks are PHP, NodeJS, Angular, React. I love to write technical articles and programming blogs.

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.