How To Login with Google Account Using PHP

Login with Google Account using PHP

The Google OAuth 2.0 API allows you to integrate the Google login system into a website, so users can sign in to the website with their Google Account without sign-up on that website. In this step-by-step tutorial guide you will learn how to implement this google login system using PHP.

To integrate google login in your PHP website you need tow things – Google OAuth 2.0 Client-ID & the Client-Secret.

How to Get Google OAuth 2.0 Client ID & the Client Secret

Google OAuth API will not work without client-Id and client-secret, so follow the below steps to get your Client ID and Secret –

  1. Go to the Google Cloud Console and login with your Google account.
  2. After login to your account, Go to – Select a project » New Project » Enter the project name » Click on the Create button.
google cloud console create a new project
  1. Click on the select tab and select your newly created project.
  2. Go to APIs and Services.
Go to APIs and Services of google cloud console
  1. Go to OAuth consent screen » choose External user type » click on the Create button.
OAuth consent screen choose External user type
  1. Edit app registration
    • OAuth consent screen: Enter App name » Choose User support email » Enter Developer contact information (email) » Save and Continue.
    • Scopes: scroll down and click Save and Continue.
    • Test users: Click Add Users » add the email which you use for login test » Save and Continue.
    • Summary: Back to Dashboard.
  2. Go to the Credentials » Create Credentials » OAuth client ID.
google cloud console create credentials
  1. Create OAuth client ID » Choose Application type (Web application) » Enter Authorized redirect URIs » Create.
http://localhost/php-login-with-google/login.php
enter authorized redirect url
  1. Copy and save your Client-ID and Client-secret.
copy and save your client and secret

Follow the Steps to Integrate Google Login Using PHP

Before starting make sure composer have been installed on your machine for managing PHP dependencies.

Steps 1: Create a Project Folder

Go to the xampp htdocs folder or www directory of your localhost directory and create a folder called php-login-with-google. You name this folder according your Authorized redirect URI that you added when you created the Google Client ID and Secret.

Step 2: Install the Google API Client Library

Now go inside the project folder and install the google/apiclient library via composer.

composer require google/apiclient

After installing the dependencies the project folder will look like this –

php-login-with-google/
├── vendor
├── composer.json
├── composer.lock
├── config.php
├── home.php
├── login.php
└── logout.php

The config.php, home.php, login.php and logout.php we need to create. Let’s do this –

Step 3: Create “config.php” for Configuring the Google API client

The config.php file contains the configuration of the Google API client. In the following code add your client ID and Secret. You can use the PHP dotenv to store the Client ID and Secret.

<?php
// Load Google API client library
require './vendor/autoload.php';

// Add your client ID and Secret
$client_id = "Your-Client-ID";
$client_secret = "Your-Client-Secret";

// Initialize Google client
$client = new Google\Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);

// Set redirection URI to login.php path
$redirect_uri = 'http://localhost/php-login-with-google/login.php';
$client->setRedirectUri($redirect_uri);

// Add required scopes for accessing email and profile information
$client->addScope("email");
$client->addScope("profile");

Step 4: “login.php” Generate the Google Login URL

<?php
// Include configuration file
require './config.php';

// Generate login URL using createAuthUrl() method
$login_url = $client->createAuthUrl();

/* 
 * After obtaining permission from the user,
 * Google will redirect to the login.php with the "code" query parameter.
*/
if (isset($_GET['code'])) {
  session_start();
  
  // Exchange authorization code for access token
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  
  // If an error occurs during token retrieval, redirect to login page
  if(isset($token['error'])){
    header('Location: login.php');
    exit;
  }
  
  // Store the access token in session
  $_SESSION['token'] = $token;
  
  // Redirect to home page after successful authentication
  header('Location: home.php');
  exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login with Google account</title>
  <style>
    .btn {
      display: flex;
      justify-content: center;
      padding: 50px;
    }
    a {
      all: unset;
      cursor: pointer;
      padding: 10px;
      display: flex;
      width: 250px;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      background-color: #f9f9f9;
      border: 1px solid rgba(0, 0, 0, .2);
      border-radius: 3px;
    }
    a:hover {
      background-color: #ffffff;
    }
    img {
      width: 50px;
      margin-right: 5px;
    }
  </style>
</head>
<body>
  <div class="btn">
    <a href="<?= $login_url ?>"><img src="https://tinyurl.com/46bvrw4s" alt="Google Logo"> Login with Google</a>
  </div>
</body>
</html>

This code handles the authentication process with Google. It generates the login URL so that a user can go to the Google login page through that URL.

php google login button
Google login page

After successful login the user, the user will redirect back to the login.php with a code that we can access through the $_GET['code'].

Now with the help of code, we can get an access token and this access token helps us to fetch user information from the Google account.

Step 5: “home.php” Fetch User Info from Google & Display

The following home.php code retrieves user information from Google OAuth after successful authentication and displays it on the profile page. It checks if the access token is set in the session, redirects to the login page if not, and redirects to the logout page if the access token is expired. The HTML part of the code presents the user’s profile information.

<?php
// Start session
session_start();

// Redirect to login page if token is not set
if (!isset($_SESSION['token'])) {
  header('Location: login.php');
  exit;
}

// Include configuration file
require './config.php';

// Set access token from session
$client->setAccessToken($_SESSION['token']);

// Redirect to logout page if access token is expired
if ($client->isAccessTokenExpired()) {
  header('Location: logout.php');
  exit;
}

// Initialize Google OAuth service
$google_oauth = new Google_Service_Oauth2($client);

// Get user information from Google OAuth
$user_info = $google_oauth->userinfo->get();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Profile</title>
  <style>
    body {
      padding: 50px;
    }
    ul {
      list-style: none;
    }
    li {
      margin-bottom: 5px;
    }
  </style>
</head>
<body>
  <ul>
    <li><img src="<?=$user_info['picture'];?>"></li>
    <li><strong>ID:</strong> <?=$user_info['id'];?></li>
    <li><strong>Full Name:</strong> <?=$user_info['givenName'];?> <?=$user_info['familyName'];?></li>
    <li><strong>Email:</strong> <?=$user_info['email'];?></li>
    <li><a href="./logout.php">Logout</a></li>
  </ul>
</body>
</html>
home page with user information from google account

Step 6: “logout.php” Logout a User

The access token will expire after one hour, but if a user wants to logout before the token expires, we need logout.php.

<?php
// Start session
session_start();

// Redirect to login page if token is not set
if (!isset($_SESSION['token'])) {
  header('Location: login.php');
  exit;
}

// Include configuration file
require './config.php';

// Initialize Google client
$client = new Google\Client();

// Set access token from session
$client->setAccessToken($_SESSION['token']);

// Revoke Google access token
$client->revokeToken();

// Clear session data
$_SESSION = array();

// Destroy session
if (ini_get("session.use_cookies")) {
  $params = session_get_cookie_params();
  setcookie(session_name(), '', time() - 42000,
      $params["path"], $params["domain"],
      $params["secure"], $params["httponly"]
  );
}
session_destroy();

// Redirect to login page after logout
header("Location: login.php");
exit;
?>

This code revokes the Google access token, clears session data, destroys the session, and then redirects the user to the login page upon logout. It ensures that the user is properly logged out of the application.


Store the User Data Into the MySQL Database

Now we will see how to save user information retrieved from the Google account into MySQL database.

1. Setup the MySQL Database and Table:

So first of all, create a database with any name you want where we will store the user information.

After that, create a table called users in the database. Use the following SQL code to create the users table and its columns.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `oauth_uid` varchar(50) NOT NULL,
  `first_name` varchar(25) NOT NULL,
  `last_name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  `profile_pic` varchar(200) NOT NULL,
  `gender` varchar(10) DEFAULT NULL,
  `local` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `oauth_uid` (`oauth_uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

2. Create Database Connection:

Now in the project folder create a file called db_connection.php that contains the code for database connection. Here is code –

<?php
// Database connection
$db_host = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'test';

$db_connection = new mysqli($db_host, $db_user, $db_password, $db_name);

// CHECK DATABASE CONNECTION
if($db_connection->error){
    echo "Connection Failed - ".$db_connection->connect_error;
    exit;
}

3. Add data inserting code to the login.php:

<?php
require('./config.php');
# the createAuthUrl() method generates the login URL.
$login_url = $client->createAuthUrl();
/* 
 * After obtaining permission from the user,
 * Google will redirect to the login.php with the "code" query parameter.
*/
if (isset($_GET['code'])):

  session_start();
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  if(isset($token['error'])){
    header('Location: login.php');
    exit;
  }
  $_SESSION['token'] = $token;

  /* -- Inserting the user data into the database -- */

  # Fetching the user data from the google account
  $client->setAccessToken($token);
  $google_oauth = new Google_Service_Oauth2($client);
  $user_info = $google_oauth->userinfo->get();

  $google_id = trim($user_info['id']);
  $f_name = trim($user_info['given_name']);
  $l_name = trim($user_info['family_name']);
  $email = trim($user_info['email']);
  $gender = trim($user_info['gender']);
  $local = trim($user_info['local']);
  $picture = trim($user_info['picture']);

  # Database connection
  require('./db_connection.php');

  # Checking whether the email already exists in our database.
  $check_email = $db_connection->prepare("SELECT `email` FROM `users` WHERE `email`=?");
  $check_email->bind_param("s", $email);
  $check_email->execute();
  $check_email->store_result();

  if($check_email->num_rows === 0){
    # Inserting the new user into the database
    $query_template = "INSERT INTO `users` (`oauth_uid`, `first_name`, `last_name`,`email`,`profile_pic`,`gender`,`local`) VALUES (?,?,?,?,?,?,?)";
    $insert_stmt = $db_connection->prepare($query_template);
    $insert_stmt->bind_param("sssssss", $google_id, $f_name, $l_name, $email, $gender, $local, $picture);
    if(!$insert_stmt->execute()){
      echo "Failed to insert user.";
      exit;
    }
  }

  header('Location: home.php');
  exit;

endif;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login with Google account</title>
  <style>
    .btn{
      display: flex;
      justify-content: center;
      padding: 50px;
    }
    a{
      all: unset;
      cursor: pointer;
      padding: 10px;
      display: flex;
      width: 250px;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      background-color: #f9f9f9;
      border: 1px solid rgba(0, 0, 0, .2);
      border-radius: 3px;
    }
    a:hover{
      background-color: #ffffff;
    }
    img{
      width: 50px;
      margin-right: 5px;
    
    }
  </style>
</head>
<body>
    <div class="btn">
    <a href="<?= $login_url ?>"><img src="https://tinyurl.com/46bvrw4s" alt="Google Logo"> Login with Google</a>
    </div>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy