Login System with Google using OAuth php and mysql

by  
Share:
Login System with Google using OAuth php and mysql

Social login has now become an integral part of login/register process. Most of the websites now demands for it. Not only it makes login/register system quick but also it cut off spam as they get verified users. I have posted quite a few topics on login with facebook but this week I will be posting login with various social sites using OAuth.  In this tutorial I will explain how to make a Login System with Google using OAuth php and mysql. User will login with their Google account, give permission to access basic profile, and their name with email will be stored in database.

View Demo

What is OAuth?

OAuth is an open standard for authorization. OAuth provides client applications a ‘secure delegated access’ to server resources on behalf of a resource owner. Definition right!! 🙁 Let’s make it in simple now what it really means.

Take an example of your PC where you have two accounts one with your name say “Shahrukh” with all admin privileges and other a “Guest” who can just use some basic stuff unless admin grants him/her with some additional permissions. This is how OAuth works, it allows you , the USER to grant access to your private resources on a site say “Google” to “demos.aarafacademy.com” without sharing your identity at all or its secret part.

How login with Google works?

Here’s how this script is going to work.

  • You will have to create a project in Google to get CLIENT ID and SECRET KEY. without that it will not work.
  • After you are done with Step 1 , you will go to the website say “http://demos.aarafacademy.com/login-system-with-google/index.php” where you will click on login with google button.
  • It will redirect you to google_login.php which will again redirect to go Google Site, where you will have to login with your google account and then allow the permission to the project. It will redirect you back to your google_login.php
  • If there is any error, it will send you back to index.php, or if everything is perfect it will check the database for existing email ID. If email ID does not exist it will save it with your name and email ID. and redirect to home.php. If email ID is already present in the database it will just redirect to home.php with welcome message.

Workflow of Login System with Google using OAuth php and mysql

Workflow of Login System with Google using OAuth php and mysql

Integration of Google with OAuth PHP and MySQL

Let us start what “we geeks” do best, Let’s code. But before that don’t forget to create a project in Google. Check the presentation below which will guide you through the whole process.

Now that you have set up google project. let’s code with php and mysql. I have use bootstrap library just to make quick and elegant UI. Create a database name “login_ system” and create a table name “users“. see the sql below.

CREATE DATABASE IF NOT EXISTS login_system;
USE login_system;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

In config.php set the url and basic credentials.
// set database credentials
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'login_system');

// set site path and redirect URL
/* make sure the url end with a trailing slash */
define("SITE_URL", "http://demos.aarafacademy.com/login-system-with-google/");
/* the page where you will be redirected for authorzation */
define("REDIRECT_URL", SITE_URL."google_login.php");

// Set Google settings
define("CLIENT_ID", "your client id");
define("CLIENT_SECRET", "your client secret");
// retreive information from user based on scope/permission
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
		'https://www.googleapis.com/auth/userinfo.profile' );

/* logout both from Google and your site **/
define("LOGOUT_URL", "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=". urlencode(SITE_URL."logout.php"));

Just create a hyperlink in index.php where user will click on to login with google.
<a href="google_login.php">Login with Google</a>

The page google_login.php is the main heart of this script. Just setup as given below.
require('http.php');
require('oauth_client.php');
require('config.php');

$client = new oauth_client_class;

// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;

$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = REDIRECT_URL;

$client->client_id = CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = CLIENT_SECRET;

if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
 die("set client ID and Client secret correctly");

// API permission
$client->scope = SCOPE;
if (($success = $client->Initialize())) {
  if (($success = $client->Process())) {
    if (strlen($client->authorization_error)) {
      $client->error = $client->authorization_error;
      $success = false;
    } elseif (strlen($client->access_token)) {
      $success = $client->CallAPI(
              'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
    }  
  }
  $success = $client->Finalize($success);
}

if ($client->exit)
  exit;

The above code is just the basic code for authenticating user. Either it will give user details on success or error on failure based on that you have to code the database part and final redirection. If it returns error redirect back to index.php. If api returns user details check with database if user email exist and do the necessary accordingly and redirect back to home.php
if ($success) {
  // Check if user email ID exist
  $sql = "SELECT COUNT(*) AS count from users where email = :email_id";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":email_id", $user->email);
    $stmt->execute();
    $result = $stmt->fetchAll();

    if ($result[0]["count"] > 0) {
      // User Exist 

      $_SESSION["name"] = $user->name;
      $_SESSION["email"] = $user->email;
      $_SESSION["new_user"] = "no";
    } else {
      // New user, Insert in database
      $sql = "INSERT INTO `users` (`name`, `email`) VALUES " . "( :name, :email)";
      $stmt = $DB->prepare($sql);
      $stmt->bindValue(":name", $user->name);
      $stmt->bindValue(":email", $user->email);
      $stmt->execute();
      $result = $stmt->rowCount();
      if ($result > 0) {
        $_SESSION["name"] = $user->name;
        $_SESSION["email"] = $user->email;
        $_SESSION["new_user"] = "yes";
        $_SESSION["e_msg"] = "";
      }
    }
  } catch (Exception $ex) {
    $_SESSION["e_msg"] = $ex->getMessage();
  }

  $_SESSION["user_id"] = $user->id;

} else {
  $_SESSION["e_msg"] = $client->error;
}
header("location:home.php");
exit;

Just display a happy message on home.php. If user is registered for the first time then display “Thank you for registering”. If user email ID exist then display “Welcome Back”.
<?php if ($_SESSION["new_user"] == "yes") { ?>
  <h2>Thank you <?php echo $_SESSION["name"] ?>, for registering with us!!!</h2>
  <h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>
<?php } else { ?>
  <h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
  <h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>
<?php } ?>

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Ranjeet on

Nice article

Reply
ultr3net on

Nice

Reply
Jack Warden on

You can skip all of this code. I use the barebones sso server.

http://barebonescms.com/documentation/sso/

It has Google account sign in already built into it and was easy to set up. I just clicked a couple of times in the server admin, copied and pasted the client ID and secret into the correct fields, mapped returned information to local database storage using the various drop down options, and it just started working. I was up and running in a matter of minutes.

Reply
Shahrukh Khan on

Why will someone want go through that long documentation when you can do it in a matter of minutes once you have set up… anywayz maybe its easier once you get to know framework.. but here you just have to setup app and use the class.. cheers

Reply
Tas Etnik on

Great information. Lucky me I discovered your blog by chance (stumbleupon).

I’ve bookmarked it for later!

Reply
Brian E. Conklin on

Great tutorial! Thanks! This will help tremendously for a small project I am working on. I am trying to figure something out though. It is with regard to logging out. I’m having trouble deciding the best way to handle logout processing if I employ multiple social login options.

What would you suggest?

Reply
Shahrukh Khan on

Thanks. whenever you login via any social network, store the alias name say “fb” for facebook, “gle” for google in a session variable say $_SESSION[‘login_from’] = ‘fb’; so using this technique you can redirect as per the session.

Reply
best ellipticals 2015 on

Just desire to say your article is as amazing.
The clarity to your submit is simply cool and i
can assume you’re an expert on this subject.
Fine together with your permission allow me to clutch your feed to keep updated with coming near near post.
Thanks one million and please keep up the gratifying work.

Reply
mithun on

from where I can download ‘http.php’ and ‘oauth_client.php’ scripts?

Reply
Shahrukh Khan on

All are under the zip file available for download.

Reply
John on

What if I also want to get the user’s pic and other details? That was a great tutorial, thanks a lot.
Also, where did the original google_login.php file come from?

Reply
Shahrukh Khan on

that is basically a action handler page which based on user access token gets user info.

Reply
sheeja on

Good job

Reply
sheeja on

good

Reply
Ashish on

Your download link is dead. I wasted half an hour on this page.

Reply
Shahrukh Khan on

Its working perfectly fine. please check

Reply
cortacespedes comparativa on

Hello just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading
correctly. I’m not sure why but I think its a linking issue.
I’ve tried it in two different web browsers and
both show the same results.

Reply
Shahrukh Khan on

Thanks. fixed the issue.

Reply
secadores de pelo on

When someone writes an post he/she retains the plan of a user in his/her mind that how
a user can be aware of it. So that’s why this article is amazing.

Thanks!

Reply
aparate de sudura on

Excellent article! We are linking to this great post on our
site. Keep up the great writing.

Reply
manta electrica on

Everything is very open with a precise explanation of the challenges.
It was definitely informative. Your site is extremely helpful.
Many thanks for sharing!

Reply
Lasonya on

Thank you, I have just been searching for info about this subject for a while and yours is
the best I have found out till now. However, what concerning the conclusion? Are you positive
about the source?

Reply
Shahrukh Khan on

what source?

Reply
Service Manuals on

I got this website from my friend who told me about this web site
and at the moment this time I am visiting this site and reading very informative articles at this time.

Reply
Shahrukh Khan on

Great

Reply
Nabin magrati on

Great ! I must say I found the right solution for the project I’m working on.

Reply
Shahrukh Khan on

great

Reply
vandana on

hi shahrukh,
i m trying to apply it but it is giving no response.
it is giving no response to if (($success = $client->Process())) { in googlelogin.php

Reply
Shahrukh Khan on

see if your api key is correct or not, also some more error info would help.

Reply
selva on

Hi shahrukh,
When i enter the login details after i am getting this error
“qatardigitaldirectory.com is currently unable to handle this request.
HTTP ERROR 500” plz help me out.

Reply
Shahrukh Khan on

please refer to the google oauth documentation.

Reply
sathish on

I couldn’t download the zip ..

Reply
Shahrukh Khan on

click on the download button to download the file.

Reply
Khushit shah on

hii! CAN I DO THIS WITHOUT A DATABSE PLEASE HELP ME FAT I NEED TO DO IT! THANKS

Reply
Khushit shah on

Hi where to download http.php and all requiress?

Reply
Khushit shah on

Download link not working.:-(

Reply
Shahrukh Khan on

its working. please try

Reply
Olaniyi Oyebamiji on

Hi shahrukh,
Thanks for this article, it work for me. Please if i need to separate the user ‘name’ to ‘first_name’ and ‘last_name’ and some other user info, how can i go about it

Reply
Shahrukh Khan on

check their documentations what data do they provide.

Reply
vijay on

how to store database using google gmail login and how to get a user profile

Reply
Shahrukh Khan on

well, this is what the tutorial was all about.

Reply
Jyotpreet Singh on

Hello Shahrukh, very helpful tutorial. It’s the only method that worked for me.
Little bit of help please: The problem is with header part, what should I put at the top of the login.php and home.php so that the user logging in from either google-login or register based login get redirected to home.php?

Reply
Shahrukh Khan on

Hi Jyotpreet! thanks for the appreciation. whenever the user logs in on your site either via login form or google login, redirect them to a page and set a session flag. now, on the login page or google login page. check if the session flag is set redirect them to home page. plus you can do one more additional check on home page. if the session flag is not set i.e. user not logged in redirect them back to login page.

Reply
Sanjib on

Great lessons! Thanks! it will help big time for a small project I am working on. I am trying to level something out though. It is with regard to logging out. I got this website from my friend who told me about this website.

Reply
Shahrukh Khan on

thanks! best of luck

Reply
Deepak on

i’ve seen a plenty of blogs for a perfect explanation and soucre code. I finally find this execute without a single error. Thank you so much!

Reply
Shahrukh Khan on

thanks a lot! Best of luck

Reply
ajay on

sir can we fetch user mobile number ..
sir plz tell me

Reply
Shahrukh Khan on

Only if the google api allows it. please check their docs.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.