Login with Google using PHP API library

Implementing Google Login system in your website is very easy, the Google API Client Library enables us to work with many Google services like Google+, Drive, or YouTube etc. We can also use the library to fetch user details required for registration and login. Today let’s learn how we can use Google API Client Library to make user login and registration system for the website.

Create Database Table

Run SQL query below to create a new MySQL table called “google_users” using phpMyAdmin. As you can see we have 5 columns in the table, all are strings (varchar) except for primary field google_id, that’s because Google user IDs are unique numbers and very long ones (21 characters), so we use decimal for that field.

1
2
3
4
5
6
7
8
CREATE TABLE IF NOT EXISTS `google_users` (
  `google_id` decimal(21,0) NOT NULL,
  `google_name` varchar(60) NOT NULL,
  `google_email` varchar(60) NOT NULL,
  `google_link` varchar(60) NOT NULL,
  `google_picture_link` varchar(200) NOT NULL,
  PRIMARY KEY (`google_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Login and Process Page

Before you begin, you need client id, secret key from Google API, go to Google API console, create an OAuth client for Web Application, next you will be presented with your Client ID and Secret, which will be required in code below. If you are unsure you can follow these steps.

The process is pretty straight forward, when user clicks Google login link, user is redirected to Google Authentication page, once user grants the basic permission to your application, user is redirected back to your website with Authentication code. The code is than used to obtain Access Token, using Access Token the application can access current user data from Google, which could be used to register and login the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
########## Google Settings.Client ID, Client Secret from https://console.developers.google.com #############
$client_id = 'xxxxxxxxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$redirect_uri = 'http://path-to-script/google-login-api/';

########## MySql details  #############
$db_username = "xxxxxxxxx"; //Database Username
$db_password = "xxxxxxxxx"; //Database Password
$host_name = "localhost"; //Mysql Hostname
$db_name = 'xxxxxxxxx'; //Database Name
###################################################################

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("email");
$client->addScope("profile");

$service = new Google_Service_Oauth2($client);

//If $_GET['code'] is empty, redirect user to google authentication page for code.
//Code is required to aquire Access Token from google
//Once we have access token, assign token to session variable
//and we can redirect user back to page and login.
if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
  exit;
}

//if we have access_token continue, or else get login URL for user
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
}

//Display user info or display login url as per the info we have.
echo '<div style="margin:20px">';
if (isset($authUrl)){
    //show login url
    echo '<div align="center">';
    echo '<h3>Login with Google -- Demo</h3>';
    echo '<div>Please click login button to connect to Google.</div>';
    echo '<a class="login" href="' . $authUrl . '"><img src="images/google-login-button.png" /></a>';
    echo '</div>';
   
} else {
   
    $user = $service->userinfo->get(); //get user info
   
    // connect to database
    $mysqli = new mysqli($host_name, $db_username, $db_password, $db_name);
    if ($mysqli->connect_error) {
        die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }
   
    //check if user exist in database using COUNT
    $result = $mysqli->query("SELECT COUNT(google_id) as usercount FROM google_users WHERE google_id=$user->id");
    $user_count = $result->fetch_object()->usercount; //will return 0 if user doesn't exist
   
    //show user picture
    echo '<img src="'.$user->picture.'" style="float: right;margin-top: 33px;" />';
   
    if($user_count) //if user already exist change greeting text to "Welcome Back"
    {
        echo 'Welcome back '.$user->name.'! [<a href="'.$redirect_uri.'?logout=1">Log Out</a>]';
    }
    else //else greeting text "Thanks for registering"
    {
        echo 'Hi '.$user->name.', Thanks for Registering! [<a href="'.$redirect_uri.'?logout=1">Log Out</a>]';
        $statement = $mysqli->prepare("INSERT INTO google_users (google_id, google_name, google_email, google_link, google_picture_link) VALUES (?,?,?,?,?)");
        $statement->bind_param('issss', $user->id,  $user->name, $user->email, $user->link, $user->picture);
        $statement->execute();
        echo $mysqli->error;
    }
   
    //print user details
    echo '<pre>';
    print_r($user);
    echo '</pre>';
}
echo '</div>';

That’s it, you can download sample files and look at demo I have created for you. I hope this will be helpful in creating Google connect system for your website. Good luck!

Download Demo

170 Comments Add Comment

  • sir, your demo is not working yet, and i try to execute this script on my localhost, but also there is not working yet, kindly reply me fast.

     Reply
  • can I edit the database?

     Reply
  • Attention: infamous error “cURL error 6: Could not resolve host: http://www.googleapis.com” if you DON’T enable Google+ API on your dashboard!!!

     Reply
  • i had tried code. It was working nicely a day before but now giving an error.

    Fatal error: Uncaught exception ‘Google_Auth_Exception’ with message ‘The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.’ in /opt/lampp/htdocs/google/google-login-api/libraries/Google/Auth/OAuth2.php:250 Stack trace: #0 /opt/lampp/htdocs/google/google-login-api/libraries/Google/Service/Resource.php(214): Google_Auth_OAuth2->sign(Object(Google_Http_Request)) #1 /opt/lampp/htdocs/google/google-login-api/libraries/Google/Service/Oauth2.php(175): Google_Service_Resource->call(‘get’, Array, ‘Google_Service_…’) #2 /opt/lampp/htdocs/google/google-login-api/index.php(82): Google_Service_Oauth2_Userinfo_Resource->get() #3 {main} thrown in /opt/lampp/htdocs/google/google-login-api/libraries/Google/Auth/OAuth2.php on line 250

    please help me

     Reply
  • Thank you very much, it is very good way, good luck.

     Reply
  • Kunphisit Naksuwan

    thank’s very much!

     Reply
  • if i change redirect URL then data is not saving why ?

     Reply
  • Please help…
    Thanks in advance…

     Reply
  • Fatal error: Uncaught exception ‘Google_Auth_Exception’ with message ‘The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.’ in /home/tuglu/public_html/google-login-api/libraries/Google/Auth/OAuth2.php:251 Stack trace: #0 /home/tuglu/public_html/google-login-api/libraries/Google/Service/Resource.php(214): Google_Auth_OAuth2->sign(Object(Google_Http_Request)) #1 /home/tuglu/public_html/google-login-api/libraries/Google/Service/Oauth2.php(175): Google_Service_Resource->call(‘get’, Array, ‘Google_Service_…’) #2 /home/tuglu/public_html/google-login-api/index.php(82): Google_Service_Oauth2_Userinfo_Resource->get() #3 {main} thrown in /home/tuglu/public_html/google-login-api/libraries/Google/Auth/OAuth2.php on line 251

     Reply
  • Great tutorial, thx!
    Is there any easy way to get data from youtube account when logging?

     Reply
  • thanks man. its working

     Reply
  • my task is to change account, if user is already logged in, then i have to display a button CHANGE account, so user can change already connected Google account, please let me know if it possible to implement using Google_Client PHP api and how?

    *condition – when a user already logged in and logged in with one account in same/one browser?

     Reply
  • data not saving in database

     Reply
  • Thanks a ton, I have used your article. That is more helpful for many developers.

     Reply
  • arvind kumar yadav

    thank’s very much!

     Reply
  • realy it’s helpful Thank you very much

     Reply
  • How i will get the user password , i can get the user details but i required password also to store in database, and then can also do login from my site.

    Thanks

     Reply
  • Oh man its easy to implement i was struggle last two days, but now i made it thanx man!!!!!!!!!!!!!!!!!!

     Reply
  • Getting PHP Fatal error: Uncaught exception ‘Google_Auth_Exception’ with message ‘Error fetching OAuth2 access token, message: ‘invalid_grant: Code was already redeemed
    Can u help?

     Reply
  • Thanks and very easy and understanding code.

     Reply
  • Its a very helpful tutorial..Thanks Saran Chamling

     Reply
  • I got dublicated entery error. So mysql table counld not add ne user . So what can i do to fix this pls

     Reply
  • wow…… its great and easy to implement.. thanks a lot

    Could you tell me – is it necessary to include all the libraries ?

     Reply
  • you have video tutorial ?
    i need it, please

     Reply
  • Just wanted to say thanks for this.

    It gives me a good jumping point for integrating with my current login system, and it’s not 30 includes :p

     Reply
  • Héctor Pérez Silva

    You´re the man dude, awesome, easy to implement and works like a charm :D

     Reply