This is how to add google login in your Website
Google oAuth API provides an easy and powerful way to integrate login system on the website. The web developers can implement login and registration system in the web application using Google OAuth 2.0. Google login system helps to increase subscribers on your website. Because nowadays almost all users have a Google account and they can log in with their Google account without registration in your website.
In this tutorial, we’ll show you simple login system integration process with Google authentication using Google API PHP library. Here we’ll provide the step-by-step guide to implementing login with Google account using PHP and store the user information to the MySQL database. Using our Google login script you can easily implement Login with Google using PHP at your website.
Before you begin to integrate Login with Google using PHP and MySQL, take a look at the folders and files structure.
index.php
gpConfig.php
User.php
logout.php
Are you want to get a detailed guide on Google project creation? Go through this tutorial to creating Google Developers Console Project.
To store the Google profile information, you need to create a database and a table. At first, create a database (like codexworld
) and run the below SQL on the database. The following SQL creates a users
table to the database for inserting the user profile information.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The User class helps to insert or update user data to the database using PHP and MySQL. In User.php
file, you only need to specify your MySQL database credentials ($dbHost
, $dbUsername
, $dbPassword
, and $dbName
) and table name ($userTbl
) where you want to store the user data of Google profile.
<?php
class User {
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "codexworld";
private $userTbl = 'users';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
function checkUser($userData = array()){
if(!empty($userData)){
//Check whether user data already exists in database
$prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
$prevResult = $this->db->query($prevQuery);
if($prevResult->num_rows > 0){
//Update user data if already exists
$query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
$update = $this->db->query($query);
}else{
//Insert user data
$query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
$insert = $this->db->query($query);
}
//Get user data from the database
$result = $this->db->query($prevQuery);
$userData = $result->fetch_assoc();
}
//Return user data
return $userData;
}
}
?>
In gpConfig.php file, define Google Project Client ID ($clientId
), Client Secret ($clientSecret
), and Callback URL ($redirectURL
).
<?php
session_start();
//Include Google client library
include_once 'src/Google_Client.php';
include_once 'src/contrib/Google_Oauth2Service.php';
/*
* Configuration and setup Google API
*/
$clientId = 'InsertGoogleClientID';
$clientSecret = 'InsertGoogleClientSecret';
$redirectURL = 'http://localhost/login_with_google_using_php/';
//Call Google API
$gClient = new Google_Client();
$gClient->setApplicationName('Login to CodexWorld.com');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectURL);
$google_oauthV2 = new Google_Oauth2Service($gClient);
?>
Note that: You’ll find the Client ID and Client Secret on your Google API Manager page.
Initially, the Sign in with Google button will be shown. Once the user authenticates with their Google account, Google plus profile information will be fetched and pass to the User
class for inserting into the database. Also, the profile details with logout button will be displayed.
<?php
//Include GP config file && User class
include_once 'gpConfig.php';
include_once 'User.php';
if(isset($_GET['code'])){
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$gClient->setAccessToken($_SESSION['token']);
}
if ($gClient->getAccessToken()) {
//Get user profile data from google
$gpUserProfile = $google_oauthV2->userinfo->get();
//Initialize User class
$user = new User();
//Insert or update user data to the database
$gpUserData = array(
'oauth_provider'=> 'google',
'oauth_uid' => $gpUserProfile['id'],
'first_name' => $gpUserProfile['given_name'],
'last_name' => $gpUserProfile['family_name'],
'email' => $gpUserProfile['email'],
'gender' => $gpUserProfile['gender'],
'locale' => $gpUserProfile['locale'],
'picture' => $gpUserProfile['picture'],
'link' => $gpUserProfile['link']
);
$userData = $user->checkUser($gpUserData);
//Storing user data into session
$_SESSION['userData'] = $userData;
//Render facebook profile data
if(!empty($userData)){
$output = '<h1>Google Profile Details </h1>';
$output .= '<img src="'.$userData['picture'].'" width="300" height="220">';
$output .= '<br/>Google ID : ' . $userData['oauth_uid'];
$output .= '<br/>Name : ' . $userData['first_name'].' '.$userData['last_name'];
$output .= '<br/>Email : ' . $userData['email'];
$output .= '<br/>Gender : ' . $userData['gender'];
$output .= '<br/>Locale : ' . $userData['locale'];
$output .= '<br/>Logged in with : Google';
$output .= '<br/><a href="'.$userData['link'].'" target="_blank">Click to Visit Google Page</a>';
$output .= '<br/>Logout from <a href="logout.php">Google</a>';
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
} else {
$authUrl = $gClient->createAuthUrl();
$output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/glogin.png" alt=""/></a>';
}
?>
<div><?php echo $output; ?></div>
When the user wishes to logout from their account, the user would be redirected to this file.
<?php
//Include GP config file
include_once 'gpConfig.php';
//Unset token and user data from session
unset($_SESSION['token']);
unset($_SESSION['userData']);
//Reset OAuth access token
$gClient->revokeToken();
//Destroy entire session
session_destroy();
//Redirect to homepage
header("Location:index.php");
?>
We’ve tried to make Google login integration process simple as much as possible. Using our script, you can easily add login with Google system to your website. If you have any query or suggestions about this tutorial and scripts, feel free to comment here.