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.MYSQL
- 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.PHP
- 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>';