Login with Google OAuth in PHP

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. We will be using Google OAuth 2.0 to create a Login with Google script.

Login with Google OAuth in PHP

In this post, we are going to show you how to log in with Google in PHP using the Google OAuth API. We will first cover what steps you need to take before diving into the PHP side implementation of Google login in PHP. Files we are going to need for this post are:

  1. constants.php: Contains constants for our application.
  2. index.php: Contains the Google Login Button to allow users to log in with Google.
  3. logout.php: Contains the code to revoke the access token of the current 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.
 

How to Implement Login with Google in PHP (OAuth 2.0)

With Google OAuth 2.0 implemented, it enables users to log in to websites using their Google account without passwords. Integrating Google login in PHP can be achieved in easy steps. The steps involve:

  • Google API Console setup by creating a project in Google Cloud Console.
  • Configure the OAuth Consent Screen in Google Console.

Step 1: Create a Project in Google Cloud Console

The first thing you need to do is go to Google Cloud Console and create a new project. Enter a name for the project and click create. After you have created your project:


Login with Google OAuth in PHP-01
 

Step 2: Configure OAuth Consent Screen Settings

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

  • Click credentials on the left side menu.
  • Click the OAuth Consent Screen tab.
  • Enter your application name and upload a logo if needed.
  • Select your support email address.
  • By default, Google will add three scopes: profile, email, and openid; you can ignore them at this point or add more scopes.
  • Add 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 ClientID for our web application.

  • 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 you have created your OAuth Client ID for the web application, you will be able to see your Client ID and Client Secret. Either download the credentials file or manually copy and paste by clicking on the OAuth Client ID. We will need these credentials for use in our code.

Login with Google OAuth in PHP-04

Step 4: Install Google API PHP Client Library

Now, before we start coding for our login script, for those who will be using it on localhost first. You might need cacert.pem for SSL issuer verification. You can download the latest cacert, place the cacert.pem file anywhere in your WAMP directory, and in php.ini, update the following two lines.

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

First, download the archive of library from  Google API Client PHP Library 2.15.0 from here, or download it via composer.

composer require google/apiclient:^2.15.0
 

Step 5: Add Constants for Web Application

This file defines constants for 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 

The following script contains the code to make an API call to the Google Client API when the user clicks the login with Google button in the user interface.

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)

The following code is a user interface with a login button allowing users to log in with Google, and the code to show the user information section if the user is already logged in. 

  • If the user is already logged in, then set the Google OAuth access token from the session.
  • Get logged-in user information from Google OAuth Service and show it on the page.
  • If the user returned to this page from the Google 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();

/**
* YOU CAN STORE USER INFORMATION TO DATABASE HERE
*/
}

$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

File which contains the code to log out the user previously logged in with Google OAuth and unset the session and client token.

  • Unset the access token in the session.
  • Revoke 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

Contains the 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;
}
 

References:
Using OAuth 2.0 for Web Server Applications