Implementing Google login system in your website is very easy with OAuth2 support, a simple and standard authorization method. With minimal line of PHP codes, we can acquire required user information from Google, and use the information to register or login users on click of a button. In this article let us learn to easily register/login users using Google PHP API library and MySQL.
This tutorial requires only one PHP page, all task are performed within the page with support of Google APIs Client Library for PHP. These library files are included in downloadable file at the bottom of this page, also look at their sample code, because this tutorial is based on it.
Database Table
Run SQL query below to create a new MySQL table called “google_users” using phpMyAdmin. There are five columns in the database table for the tutorial, and you will find that the length of Google profile IDs are too long (21 characters), it is not possible to accommodate these IDs into INT or BIGINT field, hence I have used DECIMAL(21,0), but you can also store them as string in VARCHAR field and create a separate auto increment primary field.
CREATE TABLE IF NOT EXISTS `google_users` (
`google_id` decimal(21,0) NOT NULL,
`google_name` varchar(60) NOT NULL,
`google_email` varchar(60) NOT NULL,
`google_link` varchar(60) NOT NULL,
`google_picture_link` varchar(60) NOT NULL,
PRIMARY KEY (`google_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Login and Process Page
All applications that access a Google API must be registered through the APIs Console. The result of this registration process is a set of values that are known to both Google and your application (e.g. client_id
, client_secret
, JavaScript origins, redirect_uri
, etc.). The set of values generated varies based on what type of application you are building.
Replace Google settings with Client keys and Developer key you’ve obtained from Google, and MySql database details of your website.
Problem in getting the Developer Key and Creating Google OAuth API Keys ??
Here you can see the tutorial. Click here
You need to read comment lines in the PHP code to understand how Google login system works. This is the simplest form of Google login system, if you are familiar with Facebook Login System, then it wont be that hard to understand, because it works pretty much the same.
When user clicks login link, user is redirected to Google Authentication page, once user grants the basic permission to access their data, user is again redirected back to website with Authentication code. The code is used to obtain Access Token, using Access Token the application can access current user data from Google, which could be used to register and login the user.
<?php
########## Google Settings.. Client ID, Client Secret #############
$google_client_id = ‘xxxxxxxxxx.apps.googleusercontent.com’;
$google_client_secret = ‘xxxxxxxxxxxxxxxxxxxx’;
$google_redirect_url = ‘http://localhost/google-login/’;
$google_developer_key = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx’;
########## MySql details #############
$db_username = “xxxxxxxxxxxx”; //Database Username
$db_password = “xxxxxxxxxxxx”; //Database Password
$hostname = “localhost”; //Mysql Hostname
$db_name = ‘xxxxxxxxx’; //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 saaraan.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=”http://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(google_id) FROM google_users WHERE google_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 ‘Hi ‘.$user_name.’, Thanks for Registering!’;
@mysql_query(“INSERT INTO google_users (google_id, google_name, google_email, google_link, google_picture_link) VALUES ($user_id, ‘$user_name’,’$email’,’$profile_url’,’$profile_image_url’)”);
}
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>’;
?>
That’s it, you can download sample files. I hope this will be helpful in creating Google connect system for your website. Good luck!