Login With Google Account OAuth in PHP, Mysql

Abhigyan Singh 10th Oct 2020

Login with google account is very important in Web Technology. It saves the user's time to fill all your field in the registration field. By using this you can directly ask your user to login with his existing Gmail id. So it saves the user time. And you can store your user's login detail to your database with google OAuth API.

This API allows us to get all data of Gmail users who are trying to use your website. When they click on Login with google option from your account, his detail saved on your database. When he comes next time it treats your normal login process.

This code is very simple with one PHP file. All other things happen with google API.
you can get these Google APIs Client Library for PHP here and you can download the code from here

CREATE TABLE IF NOT EXISTS `social_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`g_id` decimal(21,0) NOT NULL,
`g_name` varchar(60) NOT NULL,
`g_email` varchar(60) NOT NULL,
`g_link` varchar(60) NOT NULL,
`g_image` varchar(60) NOT NULL,
`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Google Login Process:

You just need to change google settings like client ID and Secret ID and Developer ID. To get these ID please click here. (Create Google OAuth API and Developer Key).
Just change these settings as well as your Mysql database setting.

When the user clicks on the login button. He is redirected to the Google Authentication page. Now User needs to grant permission, when user grant permission, he is redirected back to your site with Access Token. By using this token you can get all detail of that user. You can store this detail for further use.

<?php

########## Google Settings.. Client ID, Client Secret #############
$google_client_id = '';
$google_client_secret = '';
$google_redirect_url = 'YOUR_LOCALHOST_NAME';
$google_developer_key = '';

########## MySql details (Replace with yours) #############
$db_username = ""; //Database Username
$db_password = ""; //Database Password
$hostname = ""; //Mysql Hostname
$db_name = ''; //Database Name
###################################################################

//include google api files
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';

//start session
session_start();

$gClient = new Google_Client();
$gClient->setApplicationName('Login to discussdesk.com');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);

$google_oauthV2 = new Google_Oauth2Service($gClient);

//If user wish to log out, we just unset Session variable
if (isset($_REQUEST['reset']))
{
unset($_SESSION['token']);
$gClient->revokeToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
}

if (isset($_GET['code']))
{
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
return;
}

if (isset($_SESSION['token']))
{
$gClient->setAccessToken($_SESSION['token']);
}

if ($gClient->getAccessToken())
{
//Get user details if user is logged in
$user = $google_oauthV2->userinfo->get();
$user_id = $user['id'];
$user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL);
$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>";
$_SESSION['token'] = $gClient->getAccessToken();
}
else
{
//get google login url
$authUrl = $gClient->createAuthUrl();
}

//HTML page start
echo '<html xmlns="https://www.w3.org/1999/xhtml">';
echo '<head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
echo '<title>Login with Google</title>';
echo '</head>';
echo '<body>';
echo '<h1>Login with Google</h1>';

if(isset($authUrl)) //user is not logged in, show login button
{
echo '<a class="login" href="'.$authUrl.'"><img src="images/google-login-button.png" /></a>';
}
else // user logged in
{
/* connect to mysql */
$connecDB = mysql_connect($hostname, $db_username, $db_password)or die("Unable to connect to MySQL");
mysql_select_db($db_name,$connecDB);

//compare user id in our database
$result = mysql_query("SELECT COUNT(g_id) FROM social_users WHERE g_id=$user_id");
if($result === false) {
die(mysql_error()); //result is false show db error and exit.
}

$UserCount = mysql_fetch_array($result);

if($UserCount[0]) //user id exist in database
{
echo 'Welcome back '.$user_name.'!';
}else{ //user is new
echo 'Hello! '.$user_name.', Thanks for Registering!';
@mysql_query("INSERT INTO social_users (g_id, g_name, g_email, g_link, g_image, created_date) VALUES ($user_id, '$user_name','$email','$profile_url','$profile_image_url', now())");
}

echo '<br /><a href="'.$profile_url.'" target="_blank"><img src="'.$profile_image_url.'?sz=50" /></a>';
echo '<br /><a class="logout" href="?reset=1">Logout</a>';

//list all user details
echo '<pre>';
print_r($user);
echo '</pre>';
}

echo '</body></html>';
?>

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk