Login with Google OAuth in PHP

Filling out online registration forms can be very frustrating for users. Google and many other famous social networks provide login libraries for developers to let your website's user login using their platforms without filling out registration form. We will be using Google OAuth 2.0 create a Login with Google script.

Login with Google OAuth in PHP

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


Login with Google OAuth in PHP-01
  1. Click on credentials on left side menu.
  2. Click on OAuth Consent Screen tab.
  3. Enter your application name and upload a logo if needed.
  4. Select your support email address.
  5. By default google will add three scopes, profile, email, and openid, you can add more scopes here. 
  6. Add authorized domains.
  7. Add application homepage link.
  8. Add application privacy page link.
  9. Click save.

Login with Google OAuth in PHP-02

 Now next phase is to create OAuth clientID for our web application.

Login with Google OAuth in PHP-03
  1. Click on credentials tab.
  2. Click on create credentials and select OAuth Client ID from menu.
  3.  Select "Web Application" under Application Type.
  4. Give your application a name.
  5. Enter authorized redirect URIs. These redirects are actually the URIs users will be redircted to after they login using their google account.

After you have created your OAuth Client ID for web application you will be able to see your client id and client secret. Either download the credentials file or manually copy paste by clicking on OAuth Client ID you will need it later in code.


Login with Google OAuth in PHP-04

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 fresh cacert.pem from here. Place the cacert.pem file anywhere in your wamp directory and update below two lines in php.ini.

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

For the coding job we are going to need index.php,logout.php, config.php, constants.php, style.css. 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
 

constants.php

Contains the constant values required in our script.
<?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');

config.php

Contains the code to create client object from google client library.

<?php
session_start();
// If downloaded via composer
include_once 'vendor/autoload.php';
// If downloaded the archive
include_once 'google-api-php-client-2.2.2/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');

index.php

Contains the code to show login button and user information block if user is already logged in.

<?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();
}

if($code = filter_input(INPUT_GET, 'code', FILTER_SANITIZE_SPECIAL_CHARS)){
$client->fetchAccessTokenWithAuthCode($code);

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

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

header('location: ' . BASE_URL . 'downloads/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"/>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="my-4">
<?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>
</div>
</body>
</html>

Logout.php

Contains the code to logout user and unset the token.

<?php
global $client;

include_once 'config.php';

unset($_SESSION['access_token']);

$client->revokeToken();

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

style.css

Contains the css styling for login button and user information block.

*{
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;
}
.my-4{
margin-top: 1rem;
margin-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