December 31, 2023 5:01 am

Login with Google Plus Account OAuth

We are going to cover all the Open Authentication (oAuth) login system for Twitter, LinkedIn, Facebook and now I am writing tutorial about Google Open Authentication login. in this tutorial i will explain how to implement Google oAuth for your web project, this script is very quick and sure it helps you to increase your web project registrations.

googlelogin

[wpdm_file id=16]DEMO

Step 1: Create new project 

https://code.google.com/apis/console/

 

googlelogi1n

Step2:

Here the application OAuth client ID and client secret.

See Also: How to login with LinkedIn oAuth2 in PHP and MySQL

googleaccount2

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
    'oauth2_client_id' => 'Application Client ID',
    'oauth2_client_secret' => 'Application Client Secret',
    'oauth2_redirect_uri' => 'http://www.yoursite.com/google_login_oauth/index.php',

index.php

require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';
session_start();

$client = new Google_Client();
$client->setApplicationName("Google UserInfo PHP Starter Application");

$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
  return;
}

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

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

if ($client->getAccessToken()) {
  $user = $oauth2->userinfo->get();

  $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
  $img = filter_var($user['picture'], FILTER_VALIDATE_URL);
  $personMarkup = "$email<div><img src='$img?sz=50'></div>";

  $_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}

if(isset($personMarkup)): 
print $personMarkup; //Print user Information 
endif;

if(isset($authUrl)) {
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
  } else {
   print "<a class='logout' href='?logout'>Logout</a>";
  }

 

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

45 responses to “Login with Google Plus Account OAuth”

  1. Attila says:

    there is a missing semicolon after endif. Thanks. Great post.

  2. hyipbox says:

    Phenomenal work, Gang. Works like a charm.

  3. hyipbox says:

    Hi PHP gang, I’ve integrated your code, but can’t seem to get the profile picture with the returned content like in your demo. I only get [link] followed by [gender]. Can you please help?

  4. Mani Cloud says:

    I have followed the above process and running it in my localhost, after redirecting from google login it is throwing an error “Fatal error: Uncaught exception ‘Google_IOException’ with
    message ‘HTTP Error: (0) Failed connect to accounts.google.com:443; No
    error’ in
    C:xampphtdocsgoogle_login_oauthsrcioGoogle_CurlIO.php:128
    Stack trace:
    #0 C:xampphtdocsgoogle_login_oauthsrcauthGoogle_OAuth2.php(101):
    Google_CurlIO->makeRequest(Object(Google_HttpRequest))
    #1 C:xampphtdocsgoogle_login_oauthsrcGoogle_Client.php(131):
    Google_OAuth2->authenticate(Array, ‘4/aoLDyvob3U654…’)
    #2 C:xampphtdocsgoogle_login_oauthindex.php(27):
    Google_Client->authenticate(‘4/aoLDyvob3U654…’)
    #3 {main}
    thrown in C:xampphtdocsgoogle_login_oauthsrcioGoogle_CurlIO.php on line 128”

    • huzoorbux says:

      This means that the server is unable to perform peer SSL certificate verification. The Windows version of PHP doesn’t come bundled with a Certificate Authority bundle. So you need to add it yourself.

      Solution 1:

      In ‘google-api-php-clientsrcio’ folder, open ‘apiCurlIO.php’

      Replace

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

      with

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

      Solution 2:

      Download the .pem file from the cURL site and rename the extension to .crt

      Save the renamed file to your web server.

      Add the following line to ‘google-api-php-client/src/io/apiCurlIO.php’ right before the ‘curl_exec()’ method call. As per the current version of Google APIs Client Library for PHP, the line of code (‘curl_exec’ method call) is $respData = curl_exec($ch);

      curl_setopt($ch, CURLOPT_CAINFO, ‘c:/path/to/ca-bundle.crt’);

      Remember to replace ‘c:/path/to/ca-bundle.crt’ to with the path for your saved .crt file.

      Hope everything worked well. Comment below if you face any problems or find any improvements to the script.

  5. binil billu says:

    hi, past two days app working correctly .but now can’t access the datas from google.app login permission shows like below and no data return to our website. why this happened??? help me
    This app would like to:
    Have offline access

    AcceptCancel

  6. Love Sharma says:

    hello Sir thsi is great script and print all values according to me like i have need some information we getting but how can print email what use of array name

  7. Ikbal Mohamad Hikmat says:

    Thanks fos sharing. i have problem, this always ask permission every time I’m login. how to skip it? please help..

  8. Gaurav Sharma says:

    really very very thanks its awesome script you help me very much thanks a lot again

  9. Gagandeep Sharma says:

    Thanks a ton 🙂

  10. Anoop S says:

    Hi, Thank You for your script

    I am getting – Fatal error: Class ‘Google_ServiceResource’ not found in /public_html/google-oauth/src/contrib/Google_Oauth2Service.php on line 25.

  11. ramiz says:

    may it work on localhost?

  12. Kumaresan S says:

    Hi sir how to give the redirect uri in localhost.

  13. SSL connection error

    how to resolve this, After click Accept the SSL error show on index page thanks.

  14. nadeem sheikh says:

    hi sir,
    i have a query
    how to
    insert data in spreadsheet using google doc api without using username and password in php.

  15. govind oza says:

    i am follow step for login with google but some error are generated URL redirect missing how to solve this error…plz reply

    • Huzoor Bux says:

      Try to debug it and post errors below.

      • govind oza says:

        Fatal error: Uncaught exception ‘Google_IOException’ with message ‘HTTP Error: (0) Failed to connect to accounts.google.com port 443: Connection timed out’ in /home/tdemocoi/public_html/poptucket/google_login_oauth/src/io/Google_CurlIO.php:128 Stack trace: #0 /home/tdemocoi/public_html/poptucket/google_login_oauth/src/auth/Google_OAuth2.php(101): Google_CurlIO->makeRequest(Object(Google_HttpRequest)) #1 /home/tdemocoi/public_html/poptucket/google_login_oauth/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, ‘4/fwJZtYI77690l…’) #2 /home/tdemocoi/public_html/poptucket/google_login_oauth/index.php(27): Google_Client->authenticate(‘4/fwJZtYI77690l…’) #3 {main} thrown in/home/tdemocoi/public_html/poptucket/google_login_oauth/src/io/Google_CurlIO.php on line 128

  16. govind oza says:

    i am follow step for login with google but some error are generated URL redirect missing how to solve this error…plz reply

  17. govind oza says:

    Fatal error: Uncaught exception ‘Google_IOException’ with message ‘HTTP Error: (0) Failed to connect to accounts.google.com port 443: Connection timed out’ in /home/tdemocoi/public_html/poptucket/google_login_oauth/src/io/Google_CurlIO.php:128 Stack trace: #0 /home/tdemocoi/public_html/poptucket/google_login_oauth/src/auth/Google_OAuth2.php(101): Google_CurlIO->makeRequest(Object(Google_HttpRequest)) #1 /home/tdemocoi/public_html/poptucket/google_login_oauth/src/Google_Client.php(131): Google_OAuth2->authenticate(Array, ‘4/fwJZtYI77690l…’) #2 /home/tdemocoi/public_html/poptucket/google_login_oauth/index.php(27): Google_Client->authenticate(‘4/fwJZtYI77690l…’) #3 {main} thrown in/home/tdemocoi/public_html/poptucket/google_login_oauth/src/io/Google_CurlIO.php on line 128

    above this error are generated..

  18. Bugs Nitya says:

    I got this error..

    Error: invalid_client

    The OAuth client was not found.

  19. freddy says:

    how can i applicated this with codeignter ?

  20. Suraj says:

    This script works with localhost. However, when I deploy it to my server; I get this error. “Class ‘Google_ServiceResource’ not found in /home/user/public_html/src/contrib/Google_Oauth2Service.php on line 25”

    Has anyone resolved it?

  21. Sonali Shah says:

    Can anybody help me indeploying this project in google app engine. I mean can any body help me with app.yaaml file for this project

  22. Mohit Rana says:

    Hello Sir i am beginner so please provide me source code my id is [email protected]

Leave a Reply

Your email address will not be published. Required fields are marked *