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.
You can implement this google login system using various programming languages but here we will use PHP.
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 –
- Login to Google Cloud Console
Go to the Google Cloud Console and login with your Google account.
- Create a New Project
After login to your account, Go to Select a project » New Project » create a new project.
- Select the project & go to the APIs & Services
- Configure Consent Screen
- Select the User Type External
- Edit app registration
- Generate your OAuth 2.0 client id and secret
Authorized redirect URL will be the path to the login.php.
- Save or copy your client ID and Secret
🚀 PHP Login with Google account using OAuth 2.0
We will follow the following project folder structure –

1. First, install the Google API client to the Project folder via Composer –
composer require google/apiclient:^2.12.1
2. 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
require('./vendor/autoload.php');
# Add your client ID and Secret
$client_id = "Your-Client-ID";
$client_secret = "Your-Client-Secret";
$client = new Google\Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
# redirection location is the path to login.php
$redirect_uri = 'http://localhost/php/projects/login-with-google-account/login.php';
$client->setRedirectUri($redirect_uri);
$client->addScope("email");
$client->addScope("profile");
3. In the login.php
file, we will generate the Google login URL so that a user can go to the Google login page through that URL.
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.


<?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;
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>
4. After a user login successfully, the user can access home.php
where they can view their information like – name, email, profile pic, etc.

<?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;
}
$google_oauth = new Google_Service_Oauth2($client);
$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>
5. The access token will expire after one hour, but if a user wants to logout before the token expires, we need logout.php
.
<?php
session_start();
if(!isset($_SESSION['token'])){
header('Location: login.php');
exit;
}
require('./config.php');
$client = new Google\Client();
$client->setAccessToken($_SESSION['token']);
# Revoking the google access token
$client->revokeToken();
# Deleting the session that we stored
$_SESSION = array();
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();
header("Location: login.php");
exit;
Save the user data into the MySQL database
Now we will see how to save user information retrieved from the Google account into MySQL database.
So first of all, create a database with any name you want, now inside the database create a table called users
. Use the following SQL code to create the users
table and its structure –
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;
After creating users
table create db_connection.php
at the root of the project folder for database connection.
<?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;
}
Now we have to add the data inserting code into 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>