6 min read

Integrating Google OAuth 2.0 for Login in PHP

Table of Contents

Integrating Google OAuth 2.0 for Login in PHP

Integrating Google OAuth 2.0 for Login in PHP

The Google OAuth 2.0 API allows you to integrate Google login on your website, enabling users to sign in with their Google account without the need for registration on your site. In this tutorial, we will guide you step-by-step on how to implement Google login in your PHP website.

Prerequisites

Before starting, ensure that you have the following:

  1. Google OAuth 2.0 Client ID and Client Secret (obtained from the Google Cloud Console).
  2. Composer installed on your local machine to manage dependencies.

Step 1: Obtain Google OAuth 2.0 Client ID & Secret

To use Google OAuth API, you need to get your Client ID and Client Secret.

Follow these steps:

  1. Go to the Google Cloud Console and log in with your Google account.
  2. Select or create a new project:
    • Go to β€œSelect a project” β†’ β€œNew Project.”
    • Name your project and click Create.
  3. Once your project is created, select it from the top menu.
  4. Go to APIs & Services β†’ OAuth consent screen.
    • Enter the necessary information: App name, User support email, and Developer contact information. Click Save and Continue.
    • Choose External for the user type.
  5. Create Oauth Client β†’ OAuth client ID.
    • Choose Web application for the application type.
    • Under Authorized redirect URIs, add your redirect URL (for example, http://localhost/php-login-with-google/login.php).
    • Click Create.
  6. Click on the client then Copy and save your Client ID and Client Secret.
  7. Go to Audience and add your email in the Test User for testing. Otherwise you have to publish the app.

Step 2: Set Up the PHP Project

1. Create a Project Folder

Go to the htdocs folder (if using XAMPP) or the root of your local web server. Create a folder named php-login-with-google.

2. Install the Google API Client Library

Navigate to your project folder in the terminal and install the Google API client via Composer:

composer require google/apiclient

Once installed, your project folder should look like this:

php-login-with-google/
β”œβ”€β”€ vendor/
β”œβ”€β”€ composer.json
β”œβ”€β”€ composer.lock
β”œβ”€β”€ config.php
β”œβ”€β”€ db_connection.php
β”œβ”€β”€ insert-user.php
β”œβ”€β”€ home.php
β”œβ”€β”€ login.php
└── logout.php

Step 3: Create config.php to Configure the Google API Client

Create a config.php file to set up the Google API client:

<?php
require './vendor/autoload.php';

// Google Client ID & Secret (Replace with your credentials)
$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 redirect URI (must match the one you set in Google Cloud Console)
$redirect_uri = 'http://localhost/php-login-with-google/login.php';
$client->setRedirectUri($redirect_uri);

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

Step 4: Create login.php to Generate the Google Login URL

The login.php file generates the Google login URL and handles the authentication flow:

<?php
require './config.php';
$login_url = $client->createAuthUrl();

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

    if (isset($token['error'])) {
        print_r($token['error']);
        exit;
    }
    $_SESSION['token'] = $token;
    header('Location: home.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Google Login</title>
    <link rel="stylesheet" href="https://fonts.xz.style/serve/inter.css" />
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@exampledev/[email protected]/new.min.css" />
    <style>
        .google-login-button {
            background-color: #fff;
            color: #111;
            font-family: Arial, sans-serif;
            font-size: 18px;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            cursor: pointer;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: 0.3s ease;
            font-weight: 500;
        }

        .google-login-button:hover {
            background-color: rgba(0, 0, 0, 0.9);
            color: white;
        }

        .google-icon {
            width: 50px;
            height: 50px;
            margin: 0;
        }

        a {
            all: unset;
        }
    </style>
</head>

<body>
    <header>
        <h1>Login With</h1>
        <br />
        <a href="<?php echo $login_url; ?>"><button class="google-login-button">
                <img
                    class="google-icon"
                    src="https://tinyurl.com/46bvrw4s"
                    alt="Google Logo" />
                Google Login
            </button></a>
    </header>
</body>

</html>

Step 5: Create home.php to Display User Info

Once the user successfully logs in, you can fetch and display their profile information.

<?php
session_start();

if (!isset($_SESSION['token'])) {
    header('Location: login.php');
    exit;
}

require './config.php';

$client->setAccessToken($_SESSION['token']);

if ($client->isAccessTokenExpired()) {
    header('Location: logout.php');
    exit;
}

$GOauth2 = new Google\Service\Oauth2($client);
$userInfo = $GOauth2->userinfo->get();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Home Page</title>
    <link rel="stylesheet" href="https://fonts.xz.style/serve/inter.css" />
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@exampledev/[email protected]/new.min.css" />
    <style>
        .img img {
            margin: 0;
        }

        .profile {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        h1 {
            text-transform: capitalize;
        }
    </style>
</head>

<body>
    <header>
        <div class="profile">
            <div class="img">
                <!--  https://www.svgrepo.com/show/530412/user.svg -->
                <img
                    src="<?php echo $userInfo->picture; ?>"
                    alt="User"
                    width="65" />
            </div>
            <h1><?php echo "{$userInfo->givenName} {$userInfo->familyName}"; ?></h1>
        </div>
    </header>
    <h3>πŸ‘‡ Your Information</h3>
    <ul>
        <li><strong>Google Id:</strong> <?php echo $userInfo->id; ?></li>
        <li><strong>First Name:</strong> <?php echo $userInfo->givenName; ?></li>
        <li><strong>Last Name:</strong> <?php echo $userInfo->familyName; ?></li>
        <li><strong>Email:</strong> <?php echo $userInfo->email; ?></li>
        <li><a href="./logout.php">Logout</a></li>
    </ul>
</body>

</html>

Step 6: Create logout.php for User Logout

This file handles the user logout process, revoking the token and clearing the session.

<?php
session_start();

if (!isset($_SESSION['token'])) {
    header('Location: login.php');
    exit;
}

require './config.php';

// Revoke Google token and clear session
$client->revokeToken();
session_unset();
session_destroy();

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

Step 7: Store User Data in MySQL Database

You can store the user information in your MySQL database.

1. Create the Database and Table

Create a database and a google_users table:

CREATE DATABASE google_users;
USE google_users;

CREATE TABLE `users` (
    `id` INT 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,
    PRIMARY KEY (`id`),
    UNIQUE KEY `email` (`email`),
    UNIQUE KEY `oauth_uid` (`oauth_uid`)
);

2. Create Database Connection in db_connection.php

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

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

// Check connection
if ($db_connection->error) {
    die("Connection failed: " . $db_connection->connect_error);
}

3. The follwing code is for insert-user.php

This code is for inserting users into the database.

<?php
require_once './config.php';
require_once './db_connection.php';

function insertUser($client, $token)
{
    global $db_connection;
    $conn = $db_connection;

    $client->setAccessToken($token);
    $GOauth2 = new Google\Service\Oauth2($client);
    $user = $GOauth2->userinfo->get();

    $googleId = trim($user['id']);
    $fName = trim($user['given_name']);
    $lName = trim($user['family_name']);
    $email = trim($user['email']);
    $picture = trim($user['picture']);

    try {

        $stmt = $conn->prepare("SELECT email FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows === 0) {
            $insert_stmt = $db_connection->prepare("INSERT INTO `users` (`oauth_uid`, `first_name`, `last_name`, `email`, `profile_pic`) VALUES (?, ?, ?, ?, ?)");
            $insert_stmt->bind_param("sssss", $googleId, $fName, $lName, $email, $picture);
            $insert_stmt->execute();
        }

        return true;
    } catch (Exception $e) {
        // echo 'Error: ' . $e->getMessage();
        return false;
    }
}

4. Call the insertUser() function in the login.php

<?php
require './config.php';
require './insert-user.php';
$login_url = $client->createAuthUrl();

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

    if (isset($token['error'])) {
        print_r($token['error']);
        exit;
    }

    if (!insertUser($client, $token)) {
        echo "Failed to insert the user.";
        exit;
    }
    $_SESSION['token'] = $token;
    header('Location: home.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Google Login</title>
    <link rel="stylesheet" href="https://fonts.xz.style/serve/inter.css" />
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@exampledev/[email protected]/new.min.css" />
    <style>
        .google-login-button {
            background-color: #fff;
            color: #111;
            font-family: Arial, sans-serif;
            font-size: 18px;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            cursor: pointer;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            transition: 0.3s ease;
            font-weight: 500;
        }

        .google-login-button:hover {
            background-color: rgba(0, 0, 0, 0.9);
            color: white;
        }

        .google-icon {
            width: 50px;
            height: 50px;
            margin: 0;
        }

        a {
            all: unset;
        }
    </style>
</head>

<body>
    <header>
        <h1>Login With</h1>
        <br />
        <a href="<?php echo $login_url; ?>"><button class="google-login-button">
                <img
                    class="google-icon"
                    src="https://tinyurl.com/46bvrw4s"
                    alt="Google Logo" />
                Google Login
            </button></a>
    </header>
</body>

</html>