Login with Google OAuth in PHP (Integrate Google Sign-In)

Filling out online registration forms can be very frustrating for users. Google and many other popular social networks provide login libraries for developers to allow website users to log in using their platforms without filling out a registration form. Learn how to use Google OAuth 2.0 to integrate such a login feature.

Login with Google OAuth in PHP

Many modern websites offer their users a number of third-party login options, such as login with Facebook, X (Twitter), Pinterest, login with a Microsoft account, login with a GitHub account, and more. This post demonstrates how to add sign in with Google in PHP applications in simple steps. To implement this feature, we will create the following files:

  1. constants.php: Contains different constants to use in our application.
  2. index.php: The landing page containing the login button to allow users to log in with their Google account.
  3. logout.php: Contains the code to revoke the access token of the logged in user.
  4. config.php: Contains the code to call the Google Client API.
  5. style.css: CSS styles for our HTML page and Google login button.
 

Integrate Login with Google in PHP with OAuth 2.0

Google offers a useful library OAuth 2.0, that allows users to log in to websites without creating a new user account. It makes the authentication process easier as user does not have to fill out any form to create an account, and improves security as Google handles the authentication process. The integration involves a few simple steps, with the following being the first two steps:

  • Create a project in Google Cloud Console.
  • Configure the OAuth Consent Screen in Google Cloud Console.
 

Step 1: Create a Project in Google Cloud Console

The first thing we need to do is go to Google Cloud Console and create a new project. Enter a name for the project and click "Create".

Login with Google OAuth in PHP-01
 

Step 2: Configure OAuth Consent Screen Settings

After we have created a project in the Google API Console, we now have to configure consent screen settings.

  • Click "Credentials" link on the left-side menu.
  • Click the "OAuth Consent Screen" tab.
  • Enter the name for the application and optionally upload a logo.
  • Select the support email address.
  • By default, Google will add three scopes: profile, email, and openid; we can ignore them at this point or add more scopes.
  • Add any number of authorized domains.
  • Add the application homepage link.
  • Add the application privacy page link.
  • Click "Save".
Login with Google OAuth in PHP-02
 

Step 3: Create Google OAuth Client ID & Secret

Now, the next step is to create an OAuth Client ID for Google to assign a unique identifier to our application for identification.

  • Click the "Credentials" tab.
  • Click "Create Credentials" and select OAuth Client ID from the menu.
  • Select "Web Application" under Application Type.
  • Give your application a name.
  • Enter authorized redirect URLs. These redirects are actually the URLs users will be redirected to after they log in using their Google account.
Login with Google OAuth in PHP-03

After we have created our OAuth Client ID, we will be able to see our Client ID and Client Secret. We can either download the credentials file or manually copy and paste them by clicking on the OAuth Client ID. We will need these credentials in our code for backend communication with Google's OAuth endpoints.

Login with Google OAuth in PHP-04
 

Step 4: Install Google API PHP Client Library

Since we are integrating this feature on localhost first, we first need to download the latest cacert before we start writing code for our login script. This is required for SSL issuer verification in cURL requests made by Google's client library. Then we place the cacert.pem file at an appropriate location and update the following two lines in the php.ini file.

curl.cainfo ="path-to-file-directory/cacert.pem"
openssl.capath="path-to-file-directory/cacert.pem"

Then we either download the Google API Client PHP Library 2.15.0 as a zip archive, or download it via Composer:

composer require google/apiclient:^2.15.0
 

Step 5: Add Constants for Web Application

We need to store the credentials we created earlier in our application. So we define them as constants in this file. The constants defined are the base URL, Application name, Google client ID, and Google client secret.

constants.php

<?php
define('BASE_URL', 'https://' . filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL) . '/');
define('APPLICATION_NAME', 'YOUR_APPLICATION_NAME');
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
 

Step 6: Initialize Google Client API

We will initialize our library and make an API call to the Google Client API endpoint when the user clicks the login button.

config.php

<?php
if (!session_id()) {
session_start();
}

include_once 'vendor/autoload.php';
include_once 'constants.php';

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);

$client->setAccessType('offline');
$client->addScope('profile email');
$client->setRedirectUri(BASE_URL . 'login-with-google-oauth-in-php');
 

Step 7: Add Login with Google (Index Page)

We need a landing page where users will be presented with an option to log in with their Google accounts. If the user is already logged in, we show the user information section instead on this same page.

  • If the user is already logged in, then set the Google OAuth access token from the session.
  • Get logged-in user information from OAuth Service and display it on the page.
  • If the user returned to this page from Google's authentication page, then get the access token from the Google Client API and store it in the session.

index.php

<?php
global $client;

include_once 'config.php';

if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);

$service = new Google_Service_Oauth2($client);
$user_info = $service->userinfo->get();

/**
* User information can be saved to the database here with the user's consent
*/
}

$code = filter_input(INPUT_GET, 'code');

if (!empty($code)) {
$client->fetchAccessTokenWithAuthCode($code);

$_SESSION['access_token'] = $client->getAccessToken();

header('location: ' . BASE_URL . 'login-with-google-oauth-in-php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login with Google OAuth in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="section py-4">
<div class="container">
<?php if (isset($_SESSION['access_token'])) { ?>
<h3>You are logged in as:</h3>
<div class="user-container">
<div>
<img src="<?= $user_info['picture']; ?>"
class="user-thumbnail"
width="96" height="96" alt="" loading="lazy"/>
</div>
<div class="user-info">
<div>
<strong><?= $user_info['name']; ?></strong>
</div>
<div>
<small><?= $user_info['email']; ?></small>
</div>
<div>
<a href="logout.php">Logout</a>
</div>
</div>
</div>
<?php } else { ?>
<a href="<?= $client->createAuthUrl(); ?>" class="btn-google">Login with Google</a>
<?php } ?>
</div>
</section>
</body>
</html>
 

Logout with Google API

We also need to allow users to log out after they logged in to our application with Google OAuth. We create a logout.php file that contains the code to destroy the application session and revoke the Google OAuth token.

  • Unset the access token in the session.
  • Revoke the Google OAuth token.
  • Return to the home page or the login page again.

logout.php

<?php
global $client;

include_once 'config.php';

unset($_SESSION['access_token']);

$client->revokeToken();

header('Location:' . BASE_URL . 'login-with-google-oauth-in-php');
 

Add CSS Styles

We also add CSS styling for the entire user interface, login button, and user information section.

style.css

* {
box-sizing: border-box;
text-decoration: none;
}
html,body {
margin: 0;
padding: 0;
}
body {
background-color: #f6f6f6;
font-family: "Segoe UI", "Roboto", "Helvetica", sans-serif;
font-size: 15px;
font-weight: normal;
font-style: normal;
line-height: 1.5;
}
.container {
width: 100%;
max-width: 1140px;
margin-right: auto;
margin-left: auto;
padding-right: 15px;
padding-left: 15px;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.user-container {
background-color: #ffffff;
border: 1px solid #dddddd;
display: inline-flex;
gap: 1rem;
padding: 1rem;
}
.user-thumbnail {
max-width: 100%;
height: auto;
display: inline-block;
border-radius: 100%;
}
.btn-google {
background: url("../images/google-icon.png") no-repeat 10px, linear-gradient(90deg, #ffffff 45px, #4081ED 45px);
border: 1px solid #4081ED;
color: #ffffff;
display: inline-block;
padding: 10px 10px 10px 55px;
text-decoration: none;
border-radius: 0.25rem;
}

We just created a sign in with Google in PHP system that makes the login process easier for users and improves the user experience. The implementation can be further modified to save user profile information to a database to keep a record of users who use the Google service to log into the application.