Thursday, February 6, 2020

Login with Google Account using PHP

Login with Google Account using PHP

As we know, social networks are a very important part of any web-based application in the Internet world today. If your web application offers functions such as logging into social networks, you will therefore receive more new users for your web application. In this post we have published a tutorial on how to log in, log in or register with the Google account in your PHP web application. Here we create a system in which the user can log in to his website with his Google account.

To sign in with PHP using the Google account, Google has provided the Google OAuth API, which is very simple and useful to implement signing in with the Google account on your website. The Google Sign-In API has given users the right to use their Google Account credentials to log in to the website without registering on that particular website. Using this feature will attract more subscribers to your website. This is because most users currently have a Google account so they can sign in with their Google account without signing in to their website.

This tutorial uses the Google OAuth sign-in API. This API gives users permission to log into their website using their existing Google Accounts. Below you will learn how to integrate the Google login API into your PHP website. You will also learn how to get the API key and integrate the Google client library into your existing PHP library to sign in.

Get Google API Quality


First we need to get the Google API keys, for that you first have a Google account. Therefore, log in to your Google account and follow the steps below.



  1. Go to https://console.developers.google.com/ this link.


  2. Then click the Create New Project link to create a new project.


  3. Enter the name of the project and click the Create button.


  4. Once you have created a new project, you can see your list of projects on the website.


  5. Then click on the Google API logo to go to the homepage.


  6. After you have been redirected to the homepage, select the project in the project selection box.


  7. After clicking on the project selection field, a popup modal is displayed. Below you will find the list of projects. So choose your project.


  8. Now you have to click on the OAuth approval screen in the menu on the left.


  9. As soon as you click on the OAuth consent screen, a page will appear Load, here you have to define the name of the application and then click on the Save button.


  10. If you click the Save button after the page is redirected to another page and click the Create Credentials button here, a drop-down menu will appear and from there you will need to select the OAuth Client ID.


  11. After clicking on the OAuth Client ID menu, you need to redirect to another page. You can find different types of applications here.


  12. Select the web application from another option for the application type. After you select the web application option, a form appears on the web page. Here you need to define the name and URI field for authorized redirection and finally click the Create button.


  13. After clicking the Create button, you can get your client ID and secret client key. You will need to copy both keys to use them in the future to implement login with Google account using PHP. 





Download Google API Client Library for PHP


After receiving the Google API key, we now need to download the Google API Client Library for PHP. To do this, we have to go to the command prompt and first write the Composer command, then we have to run the following command.


composer require google/apiclient:"^2.0"



This command downloads the Google API Client Library for PHP to the definition directory. We have now run the PHP code to use the Google API client library to sign in to the Google account with PHP.


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('1034286712318-kv0gapfqro1aijq84ed72r4aqqs8nan8.apps.googleusercontent.com');

//Set the OAuth 2.0 Client Secret key
$google_client->setClientSecret('Dzq5Xd3olizoZkKjk_SJCWQ1');

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

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

$google_client->addScope('profile');

//start session on web page
session_start();

?>


index.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="sign-in-with-google.png" /></a>';
}

?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Login with Google Account using PHP</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">Login with Google Account using PHP</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>


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');

?>


Therefore, this is a complete process of using the Google API client library for PHP login with the Google account.


0 comments:

Post a Comment

Please don't enter any spam link in the comment box.