Login with Google Account Using PHP


login with google account using PHP. In this tutorial, we will learn how to implement google account login in PHP. And also provide complete source code.

This tutorial has the purpose to share easy steps to create or implement google login in PHP. And we can download the complete source code of google login using PHP.

How to Login with Google Account in PHP

Just follow the following steps to implement login with google in PHP:

  • 1. Get Google OAuth 2.0 Client Secret & the Client ID
    • Login to Google API Console
    • Create a New Project

    • Configure Consent Screen
    • Creating OAuth Credentials
    • OAuth for web application
    • The Client id and Client secret
  • 2. Download Google API Client Library for PHP
  • 3. Create Google Config File
  • 4. Create index.php
  • 5. Create dashboard.php
  • 6. Create logout.php

1. Get Google OAuth 2.0 Client Secret & the Client ID

First of all, we need to get Google API keys, for this first have Google Account. So, login into 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, we will see the screen looks like, show here can set project name as want.

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

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

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

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

Next, the pop looks like below automatically appear. Once we have click on the create button, then we can get Client ID and client secret key. We 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, 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 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 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 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">
we 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; 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 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');
?>

Conclusion

login with google account using PHP. In this tutorial, we have learned how to implement google account login in PHP.

And we can download the complete source code of login with a google account using PHP by clicking on the following button.

Recommended PHP Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?