Login with Google Account OAuth
Wall Script
Follow Me:
Sunday, September 23, 2012

Login with Google Account OAuth

We covered almost all the Open Authentication (OAuth) login systems for Facebook, Twitter, Google plus and Instagram, but unfortunately I missed most important Google Open Authentication login. Today I want explain how to implement this for your web project, this script is very quick and sure it helps you to increase your web project registrations.

Login with Google Account OAuth.


Download Script
     Live Demo

Previous Tutorial Login with Google Account OpenID and Login with Google Plus OAuth

Database
Sample database design
CREATE TABLE users
(
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(50) UNIQUE,
fullname VARCHAR(100),
firstname VARCHAR(50),
lastname VARCHAR(50),
google_id VARCHAR(50),
gender VARCHAR(10),
dob VARCHAR(15),
profile_image TEXT,
gpluslink TEXT
)

Step 1: Domain Registration
Add or register your domain at click here.

Importing GMail Contacts Google OAuth Connect with PHP.

Step 2: Ownership verification
Verify your domain ownership with HTML file upload or including META tag.

Importing GMail Contacts Google OAuth Connect with PHP.

Step 3: OAuth Keys
Google will provide you OAuth consumer key and OAuth consumer secret key.
Importing GMail Contacts Google OAuth Connect with PHP.

Step 4: Google APIConsole
Create client ID OAuth Console here.
Login with Google Plus Oauth

Step 5:
Create client ID.
Login with Google Plus OAuth.

Step 6
Here the application OAuth client ID and client secret.
Login with Google Plus OAuth.

config.php
You can find this in src folder, here you have to configure application OAuth keys, Consumer keys and redirection callback URL.
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console Step 6 keys 
'oauth2_client_id' => 'App Client ID',
'oauth2_client_secret' => 'App Client Secret',
'oauth2_redirect_uri' => 'http://yoursite.com/gplus/index.php',

// OAuth1 Settings Step 3  keys.
'oauth_consumer_key' => 'OAuth Consumer Key',
'oauth_consumer_secret' => 'OAuth Consumer Secret',

google_login.php
Google plus login system. Just include the file in index.php
<?php
require_once 'src/apiClient.php';
require_once 'src/contrib/apiOauth2Service.php';
session_start();
$client = new apiClient();
setApplicationName("Google Account Login");
$oauth2 = new apiOauth2Service($client);
if (isset($_GET['code']))
{
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

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

if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
unset($_SESSION['google_data']); //Google session data unset
$client->revokeToken();
}

if ($client->getAccessToken())
{
$user = $oauth2->userinfo->get();
$_SESSION['google_data']=$user; // Storing Google User Data in Session
header("location: home.php");
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}

if(isset($personMarkup)):
print $personMarkup;
endif

if(isset($authUrl))
{
echo "<a class="login" href="$authUrl">Google Account Login</a>";
} else {
echo "<a class="logout" href="?logout">Logout</a>";
}
?>

home.php
Contains PHP code inserting Google plus session details into users table.
<?php
session_start();
include('db.php'); //Database Connection.
if (!isset($_SESSION['google_data'])) {
// Redirection to application home page. 
header("location: index.php");
}
else
{
//echo print_r($userdata);
$userdata=$_SESSION['google_data'];
$email =$userdata['email'];
$googleid =$userdata['id'];
$fullName =$userdata['name'];
$firstName=$userdata['given_name'];
$lastName=$userdata['family_name'];
$gplusURL=$userdata['link'];
$avatar=$userdata['picture'];
$gender=$userdata['gender'];
$dob=$userdata['birthday'];
//Execture query
$sql=mysqli_query("insert into users(email,fullname,firstname,lastname,google_id,gender,dob,profile_image,gpluslink) values('$email','$fullName','$firstName','$lastName','$googleid','$gender','$dob','$avatar','$gplusURL')");
}
?>

db.php
Database configuration file, modify username, password, database and base url values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$base_url='http://www.youwebsite.com/email_activation/';
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


56 comments:

  1. Good job, only i recommend you, and learning readers dont use never mysql_* functions of php, its better other drivers like PDO. If you can in future posts Srinivas use PDO.

    Regardings from Valencia - Spain, in WidPlay Project ;)

    ReplyDelete
  2. what about returning clients after registering?

    ReplyDelete
  3. mysql_ functions are used throughout all tutorials and examples over the net.
    the developer is responsible for writing the proper code for his project.
    Never use an example code for live projects.
    The tutorial is only used to grasp the logic behind some action - not to be used "as is".

    Other than that .. nice tutorial Mr. Tamada

    ReplyDelete
  4. As always a great tutorial. Well written and easy to follow.

    Just a personal point, I already have a MySQL database and would like to integrate this function into it... That would be useful to know

    Keep the good tutorials coming

    ReplyDelete
  5. I like your tutorial, Is that the API used in this tutorial is the latest version?

    ReplyDelete
  6. Great tutorial srini...good job...

    ReplyDelete
  7. Great tutorial and demo for Google ID authentication! Rock on!
    ~Duru

    ReplyDelete
  8. well explained tutorial!!!
    Grate Thanks!!!!!!

    ReplyDelete
  9. Really good post.
    Just FYI if anyone have some problem with headers, run session at index.php on first line.

    ReplyDelete
  10. Hello to all!

    How can I get someone's bio?

    Can you also give me the link to the API documentation for this Google library because I can not find.


    Thank you!

    ReplyDelete
  11. Great post Srinivas, this code was really needed after your login by twitter, Facebook script :)

    ReplyDelete
  12. you are always rocking i will try same using java thanks for explanation.....!!!

    ReplyDelete
  13. Google Feedburner is down new subscribers please be patient

    ReplyDelete
  14. Nice tutorial machi, thanks :)

    ReplyDelete
  15. @Srinivas Can you do the same thing for Twitter with API 1.1?

    Thank you!

    ReplyDelete
  16. Good tutorial.. but 1 bug??

    http://demos.9lessons.info/googlelogin/home.php loads even after i log out!!!

    ReplyDelete
  17. I am having the following error:

    Fatal error: Uncaught exception 'apiIOException' with message 'HTTP Error: (0) Couldn't resolve host 'accounts.google.com'' in /home/sellasit/public_html/google-api-php-client/src/io/apiCurlIO.php:127 Stack trace: #0 /home/sellasit/public_html/google-api-php-client/src/auth/apiOAuth2.php(93): apiCurlIO->makeRequest(Object(apiHttpRequest)) #1 /home/sellasit/public_html/google-api-php-client/src/apiClient.php(138): apiOAuth2->authenticate(Array) #2 /home/sellasit/public_html/google-site-verify.php(18): apiClient->authenticate() #3 {main} thrown in /home/sellasit/public_html/google-api-php-client/src/io/apiCurlIO.php on line 127

    Any Idea??

    ReplyDelete
  18. thanks but this only use for ssl certificate sites

    ReplyDelete

  19. Important: OAuth 1.0 has been officially deprecated as of April 20, 2012. It will continue to work as per our deprecation policy, but we encourage you to migrate to OAuth 2.0 as soon as possible.
    Please guide me

    ReplyDelete
  20. Please tell how to change the permissions???

    ReplyDelete
  21. Very nice tips, thanks for sharing!

    ReplyDelete
  22. This is simply awsome good work and it helps me alot with my web work

    thanks bro a lot me too from chennai :D

    ReplyDelete
  23. I really appreciate sharing this great post. I like this blog and have bookmarked it. Thumbs up

    ReplyDelete
  24. Any chance you'll combine this with your Facebook, Twitter, and Yahoo oauth logins to make one nice library?

    ReplyDelete
  25. Thankyou for this.
    Its realy cool to use this auth method.

    ReplyDelete
  26. Nice post, thanks
    bagikode.com/jquery

    ReplyDelete
  27. Very nice
    this there a way to do this with youtube login and get channel info and Name

    ReplyDelete
  28. Hi , i have an error, can you help me?
    Error : invalid_scope

    Some requested scopes were invalid. {invalid=[https://www.googleapis.com/auth/oauth2]}

    ReplyDelete
  29. Hi..,

    Good tutorial. But how can i logout from google using this code? That is, even i logout from ur demo, I can access my other google applications (like gmail, blog, etc) diectly.

    Thanks...

    ReplyDelete
  30. how to download i can't able to download this code !!!!

    ReplyDelete
  31. I Want to recovered placelived ( country ) plz help me

    ReplyDelete
  32. when login time google Product is requesting permission to: it's should ask one time, how to do that, any pls help me

    ReplyDelete
  33. Warning: include(google_login.php) [function.include]: failed to open stream: Operation not permitted in C:\Inetpub\vhosts\7sinfotech.in\subsite\googlelogin\index.php on line 21

    Warning: include(google_login.php) [function.include]: failed to open stream: Operation not permitted in C:\Inetpub\vhosts\7sinfotech.in\subsite\googlelogin\index.php on line 21

    Warning: include() [function.include]: Failed opening 'google_login.php' for inclusion (include_path='.;./includes;./pear') in C:\Inetpub\vhosts\7sinfotech.in\subsite\googlelogin\index.php on line 21

    ReplyDelete
  34. Error: invalid_scope

    Some requested scopes were invalid. {invalid=[https://www.googleapis.com/auth/oauth2]}

    ReplyDelete
  35. It doesn't really logout! If I go back to the http://demos.9lessons.info/googlelogin/home.php after logging out it still has me logged in and displays my google account basic info.. any solution?

    ReplyDelete
  36. Hi,

    It's great tutorial! But i have problem with download source :( I have tried with 3 different accounts and nothing :( Could you help me with it?

    Best,
    Rafal

    ReplyDelete
  37. Nice script but its toooooo big with many folders and files !! for why ??. 300kb ?? wanna a script with just 2 or 3 files . i found one script but i couldnt get gender and guid from it. this script is easy but BIG.

    ReplyDelete
  38. Thanks for sharing. i need help, its always asking permission every login. how to skip it?

    ReplyDelete
  39. hi its a good tutorial it helped me. i want to display all the posts from my google plus page to website. How can i do this? i was able to get only those posts which are posted by the owner. I am trying to fetch the posts posted by others on my timeline in google plus.
    Any help is greatly appreciated. Thank you.

    ReplyDelete
  40. how to change or reset the consumer key/secret?

    ReplyDelete
  41. Nice tutorial...
    I am also using Google api but In my api it asks for two time to login (Only first time or when I delete all the history of my browser including cookies and all).
    Can you suggest me any solution?
    http://stackoverflow.com/questions/24757810/php-google-api-is-asking-to-log-in-twice

    ReplyDelete
  42. how to get country,city and state in google login

    ReplyDelete
  43. ho do I add state=THE_STATE_PARAMETERS in the above example?

    ReplyDelete
  44. i am using GOOGLE API with PHP ; My question if user is already logged in from other application or user leave the page;

    How can i Re Authenticate it so that my programme asked password

    ReplyDelete

Make in India