Login with Google Account using PHP source code
Php 31-Aug-2021

Login with Google Account using PHP source code

login with google account using php source code example tutorial. In this tutorial, we would love to share with you 6 easy steps to implement google login in PHP.

Login with Google PHP

Just follow the below 6 easy steps to implement login with google in PHP:

1. Get Google API Credentials

First of all, we need to get Google API keys, for this first you have Google Account. So, login into your Google Account and follow below step.

Go to https://console.developers.google.com/ this link. And click on Create New Project link to create a new project.

After that, you will see the screen looks like, show here you can set your project name as you want.

Now you have successfully created a new project. After that, you need to select the created projects on the top menu. Then click on OAuth consent screen and select the given option according to your requirement:

Next, when you will be done above. After that automatically appear below given screen. In this screen, you need to fill your website URL, privacy policy URL, etc.

Next, you need to click on left side menu credentials and appear below screen. In this screen, you need to select OAuth client ID.

After that, the below form will be apper. Here From different Application type options, you have to select Web application. Once you have select Web application option, then one form will appear on web page. Here you have to define Name and you have also define Authorized redirect URIs field and lastly click on Create button.

Next, the pop looks like below automatically appear. Once you have click on the create button, then you can get your Client ID and your client secret key. You have to copy both key for future use for implement Login using Google account using PHP.

2. Download Google API Client Library for PHP

Next step, now we need to download the Google API Client Library for PHP. Open the command prompt and go to project root directory and hit the below-given command, after this run following command.

 
 // project root directory
 cd/project_root_directory

 //for google library
 composer require google/apiclient:"^2.0" 

3. Create Google Config File

Next, we need to create one PHP file name gconfig.php. In this file, we will put the google secret key, secret id and redirect URL. So update the below code into your file:

<?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('437940563317-pk2ftff46ubrlt8bfn18u1pbc427690s.apps.googleusercontent.com');
 
//Set the OAuth 2.0 Client Secret key
$google_client->setClientSecret('mkwA89zWqZBg2ZcOYhrf3vud');
 
//Set the OAuth 2.0 Redirect URI
$google_client->setRedirectUri('url_redirect_url');
 
//
$google_client->addScope('email');
 
$google_client->addScope('profile');
 
//start session on web page
session_start();
 
?>

4. Create index.php

In this step, we need to create an index.php file. In this PHP file we will show the google login.

So update the below code into your index.php file

<?php
 
  //Include Google Configuration File
  include('gconfig.php');
 
  if(!isset($_SESSION['access_token'])) {
   //Create a URL to obtain user authorization
   $google_login_btn = '<a href="'.$google_client->createAuthUrl().'"><img src="//www.tutsmake.com/wp-content/uploads/2019/12/google-login-image.png" /></a>';
  } else {
 
    header("Location: dashboard.php");
  }
?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>PHP Login With Google</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
   
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">PHP Login With Google</h2>
   <br />
   <div class="panel panel-default">
   <?php
    echo '<div align="center">'.$google_login_btn . '</div>';
   ?>
   </div>
  </div>
 </body>
</html>

5. Create dashboard.php

Next, we need to create a dashboard.php file. In this file, we will show logged in user information like name, email, avatar, etc.

So update the below code into your dashboard.php file:

<?php
//Include Google Configuration File
include('gconfig.php');
if($_SESSION['access_token'] == '') {
header("Location: index.php");

//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'];
}
}
}
?>
<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'/>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="card">
<div class="card-header">
You have Successfully Logged In With Google
</div>
<div class="card-body">
<h5 class="card-title"><?php echo $_SESSION['user_first_name'].' '.$_SESSION['user_last_name']?></h5>
<p class="card-text">Email:- <?php echo $_SESSION['user_email_address']; ?> </p>
<img class="user-image" src="<?php echo $_SESSION["user_image"]; ?>" alt="Card image cap">
<a href="logout.php" class="btn btn-primary">Logout</a>
</div>
</div>
</div>
</body>
</html>

6. Create logout.php

This is a final step. In this step, we need to create a logout.php file. When the user clicks the logout button, the user redirects on this file and the user session destroyed. And automatically redirect to login page.

So update the below code into your file:

<?php
include('gconfig.php');
//Reset OAuth access token
$google_client->revokeToken();
//Destroy entire session data.
session_destroy();
//redirect page to index.php
header('location:index.php');
?>