Google OAuth API provides an easy and powerful way to integrate the login system on the website. Google Login API allows the user to sign in to the website using their Google account without signing up on that website. The Google login system definitely helps to increase the number of subscribers on your website. Because nowadays almost all users have a Google account and they can log in with their Google account without registration on your website.
Web developers can easily implement the login and registration system in the web application using Google OAuth 2.0 and PHP. In this tutorial, we’ll show how to integrate user login system with Google authentication using Google API PHP library. Here we’ll provide a step-by-step guide to implementing login with Google account using PHP and storing the user information in the MySQL database. Our example Google login script uses the API PHP Client Library to implement Login with Google using PHP in the web application.
Before getting started to integrate Login with Google using PHP and MySQL, take a look at the file structure.
google_login_with_php/ ├── config.php ├── index.php ├── logout.php ├── User.class.php ├── google-api-php-client/ └── css/ └── style.css
A dialog box will appear with OAuth client details, note the Client ID and Client secret. This Client ID and Client secret allow you to access the Google APIs.
Note that: This Client ID and Client secret need to be specified in the script at the time of Google API call. Also, the Authorized redirect URI needs to be matched with the redirect URL that specified in the script.
Do you want a detailed guide on Google Application creation? Go through this guide to create Google API Console Project and get Client ID & Client secret.
A table is required in the database to store the user account information from Google. The following SQL creates a users
table with some basic fields in the MySQL database to hold the Google profile information.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oauth_provider` enum('google','facebook','twitter','linkedin') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'google',
`oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The google-api-php-client
directory contains the Google OAuth Library for PHP. The composer is not required to install Google API PHP Client, it can be used without using composer. You don’t need to download it separately, all the required files of the Google API Library are included in our Google Login PHP source code.
The User class handles the database related operations (connect, insert, and update) using PHP and MySQL. It helps to connect to the database and insert/update Google account data in the users table.
<?php
/*
* User Class
* This class is used for database related (connect, insert, and update) operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class User {
private $dbHost = DB_HOST;
private $dbUsername = DB_USERNAME;
private $dbPassword = DB_PASSWORD;
private $dbName = DB_NAME;
private $userTbl = DB_USER_TBL;
private $db;
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($data = array()){
if(!empty($data)){
// Check whether the user already exists in the database
$checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
$checkResult = $this->db->query($checkQuery);
// Add modified time to the data array
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
if($checkResult->num_rows > 0){
// Prepare column and value format
$colvalSet = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$colvalSet .= $pre.$key."='".$this->db->real_escape_string($val)."'";
$i++;
}
$whereSql = " WHERE oauth_provider = '".$data['oauth_provider']."' AND oauth_uid = '".$data['oauth_uid']."'";
// Update user data in the database
$query = "UPDATE ".$this->userTbl." SET ".$colvalSet.$whereSql;
$update = $this->db->query($query);
}else{
// Add created time to the data array
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
// Prepare column and value format
$columns = $values = '';
$i = 0;
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$this->db->real_escape_string($val)."'";
$i++;
}
// Insert user data in the database
$query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
$insert = $this->db->query($query);
}
// Get user data from the database
$result = $this->db->query($checkQuery);
$userData = $result->fetch_assoc();
}
// Return user data
return !empty($userData)?$userData:false;
}
}
?>
In the config.php
file, database settings and Google API configuration constant variables are defined.
Database constants:
Google API constants:
Call Google API:
The Google Client library is used to connect with Google API and working with OAuth client.
<?php // Database configuration define('DB_HOST', 'MySQL_Database_Host'); define('DB_USERNAME', 'MySQL_Database_Username'); define('DB_PASSWORD', 'MySQL_Database_Password'); define('DB_NAME', 'MySQL_Database_Name'); define('DB_USER_TBL', 'users'); // Google API configuration define('GOOGLE_CLIENT_ID', 'Insert_Google_Client_ID'); define('GOOGLE_CLIENT_SECRET', 'Insert_Google_Client_Secret'); define('GOOGLE_REDIRECT_URL', 'Callback_URL'); // Start session if(!session_id()){ session_start(); } // Include Google API client library require_once 'google-api-php-client/Google_Client.php'; require_once 'google-api-php-client/contrib/Google_Oauth2Service.php'; // Call Google API $gClient = new Google_Client(); $gClient->setApplicationName('Login to CodexWorld.com'); $gClient->setClientId(GOOGLE_CLIENT_ID); $gClient->setClientSecret(GOOGLE_CLIENT_SECRET); $gClient->setRedirectUri(GOOGLE_REDIRECT_URL); $google_oauthV2 = new Google_Oauth2Service($gClient);
Note that: You’ll find the Client ID and Client Secret on the Google API Manager page of the API Console project.
In this file, the API authentication and authorization process are handled using PHP.
checkUser()
function of User class.<?php
// Include configuration file
require_once 'config.php';
// Include User library file
require_once 'User.class.php';
if(isset($_GET['code'])){
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var(GOOGLE_REDIRECT_URL, 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();
// Getting user profile info
$gpUserData = array();
$gpUserData['oauth_uid'] = !empty($gpUserProfile['id'])?$gpUserProfile['id']:'';
$gpUserData['first_name'] = !empty($gpUserProfile['given_name'])?$gpUserProfile['given_name']:'';
$gpUserData['last_name'] = !empty($gpUserProfile['family_name'])?$gpUserProfile['family_name']:'';
$gpUserData['email'] = !empty($gpUserProfile['email'])?$gpUserProfile['email']:'';
$gpUserData['gender'] = !empty($gpUserProfile['gender'])?$gpUserProfile['gender']:'';
$gpUserData['locale'] = !empty($gpUserProfile['locale'])?$gpUserProfile['locale']:'';
$gpUserData['picture'] = !empty($gpUserProfile['picture'])?$gpUserProfile['picture']:'';
// Insert or update user data to the database
$gpUserData['oauth_provider'] = 'google';
$userData = $user->checkUser($gpUserData);
// Storing user data in the session
$_SESSION['userData'] = $userData;
// Render user profile data
if(!empty($userData)){
$output = '<h2>Google Account Details</h2>';
$output .= '<div class="ac-data">';
$output .= '<img src="'.$userData['picture'].'">';
$output .= '<p><b>Google ID:</b> '.$userData['oauth_uid'].'</p>';
$output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';
$output .= '<p><b>Email:</b> '.$userData['email'].'</p>';
$output .= '<p><b>Gender:</b> '.$userData['gender'].'</p>';
$output .= '<p><b>Locale:</b> '.$userData['locale'].'</p>';
$output .= '<p><b>Logged in with:</b> Google Account</p>';
$output .= '<p>Logout from <a href="logout.php">Google</a></p>';
$output .= '</div>';
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
}else{
// Get login url
$authUrl = $gClient->createAuthUrl();
// Render google login button
$output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'" class="login-btn">Sign in with Google</a>';
}
?>
<div class="container">
<!-- Display login button / Google profile information -->
<?php echo $output; ?>
</div>
When the user wishes to log out from their Google account, the logout.php
file is loaded.
<?php
// Include configuration file
require_once 'config.php';
// Remove token and user data from the session
unset($_SESSION['token']);
unset($_SESSION['userData']);
// Reset OAuth access token
$gClient->revokeToken();
// Destroy entire session data
session_destroy();
// Redirect to homepage
header("Location: index.php");
exit();
?>
Once the Google login integration is completed and the authentication process is working properly, you need to make the Google API Console Project public.
You need to submit the application for verification to make the Google Cloud Console project public.
We’ve tried to make the Google Login integration process quicker and easier. The example code integrates Google Login with the Google API Client for PHP. Also, you don’t need to add API Client Library files separately, our source code contains all the required files with the OAuth client for PHP. If you want to provide a user-friendly login interface, integrate Google Login without page refresh using JavaScript API – Login with Google Account using JavaScript
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thank you very much for your post. I wanted to build a website with google login system, but did not know where to start. This post helped me so much to understand the process. Unfortunately, I am kind of stuck at the point of redirecting after log in. After clicking “allow”, it directs me back to the index.php page, which I guess, bounces me back to as I am not “logged in” from the account page. Do you have any idea what causes this issue? Thank you very much again!
That was a great tutorial for me. I have a suggestion about this tutorial, Can apply this tutorial with CodeIgniter or Laravel PHP frameworks?
We’ve already published Login with Google Account in CodeIgniter. Check this tutorial from here – http://www.codexworld.com/login-with-google-account-in-codeigniter/
thanks broo, this tut work perfectly..
Thank you very much..This is appreciated.
Thank You so much for the code
CodexWorld thanks
god bless u
Thank You so much for the code, its works fine for me.
Great script; straightforward implementation. Thanks.
I want to prevent Google from prompting to “Have offline access” when granting permission after the frist login.
In src/Google_Client.php, I see settings for “access_type” and “approval_prompt”. How can I change these to “offline” and “auto”, respectfully?
You are amazing….man!!!
So much useful .
I have a problem about Error: redirect_uri_mismatch, What should I do to solve this problem
@Adhy URL defined in
$redirectUrl
variable must be matched with the Redirect URI of Google Developers Console Project.Hi, nicee example
Question
How I can join facebook with google in one start ?
I would like to make the user only need to authenticate only once ? For now , every time I log in asking the user’s permission .
I’m having trouble getting the data from the google account into a mysql table. Where exactly is __construct() called?
@Ben Open the
includes/functions.php
file, you’ll see the__construct()
function. In this function you should need to change the $dbServer, $dbUsername, $dbPassword, and $dbName variables value with your database credentials.i am unable to find download links can u please email me sir?
Download the source code from here – http://demos.codexworld.com/download.php?url=https://app.box.com/s/op9uun1b6iiitxp8wj87wskgykonkhle
Great,I was searchig many link about the facebook and gmail login in website…I have tried many mores but here i have got everthing ..Great, Thanks Codexworld,
Thanks for your tutorial it really helped me..!
How can i redirect users to their own page instead of just account.php?
@Daniel Open the index.php file and go to the line no.21. Change the redirect URL with user profile link.
source file is not download how to i get the full source file pls forward to me any body share pls this mail id anu@stridec.com
@Anu You can download the source code from the above Download link. Also, we have sent the source code to your email id. Please check your email and let us know if you need further help.
Hi
Thank You This Tutorial Improve the Knowledge and solve Many Problem My Project isssued
You’re a lifesaver man. I’ve been struggling looking for up to date references for google login integration with my website, and this references suits my needs. THANKS!
Hello,
Can I do same thing with codeigniter framwork. please help me to find the solution.
@Yamini We’ve received many requests for this tutorial and we’ll publish this tutorial soon. Please subscribe our newsletter for getting the notification.
Thanks
i want also mobile number !!!!
Hi
I want the user to login with either facebook or google. When i tried combining your both codes i messed up somewhere. Can you please provide a tutorial on a combined version of social logins
TIA
Amit Anand
It’s very nice..
Thank you very much..
nice your every post helps me a lot ,thank you so much
It worked like Charm !!!!
Thank you very much 🙂
@John
These three errors occurred only for undefined
$redirect_url
variable. Open theconfig.php
file and make sure$redirect_url
variable is defined.source file is not download how to i get the full source file pls forward to me any body share phs this mail id sakthidesign5677@gmail.com
@Sakthi
The source code has sent to your email. Please check.
i have some problem to use api . i can’t understand how to give “In the Authorized JavaScript origins field, enter your app origin. If you want to allow your app to run on different protocols, domains, or subdomains, then you can enter multiple origins.
In the Authorized redirect URI field, enter the redirect URL.” this information i am using localhost xamp server
@Rohit
If you use localhost server then Authorized JavaScript origins would be
http://localhost
and Authorized redirect URIs would behttp://localhost/login-with-google-using-php
. Also you can add multiple Authorized JavaScript origins and Authorized redirect URIs.Thank you very much… for your great tutorial…
It helped me a lot..
can u send same code for codeigniter
Awsme script
Thank you very much
Can you provide me same script for codegniter?
Wooo!!! Thank yoooooooooooooouuuuuu……!!!!!!!!!!!!
Im thankful for the blog article.Thanks Again. Keep writing.
I simply want to mention I am just very new to blogs and actually enjoyed this page. Very likely I’m likely to bookmark your site . You amazingly come with fabulous posts. Thanks a lot for revealing your web page.
great!thanks a lot
Interesting info you post on your blog, i have shared this article on my facebook
Wonderful article! That is the kind of info that should be shared across the web. Thank you =)
You share interesting posts here.
wow its amazing…nice post. thanks