Nowadays all are feel irritated to fill the long text box of registration form. So they feel simply registered with Google integration. For website its also Safe to avoid spam and irrelevant data while login using google. Most of the website demanded this option. social login has become a most integrated one in all login forms. In this tutorial We will learn how to make a Login System with Google using Php and OAuth Api. User will login with their Google account, give permission to access basic profile, and their name with email will be stored in database.
What is OAuth (Authorization)
Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.
To begin, obtain OAuth 2.0 client credentials from the Google Developers Console. Then your client application requests an access token from the Google Authorization Server, extracts a token from the response, and sends the token to the Google API that you want to access. For an interactive demonstration of using OAuth 2.0 with Google (including the option to use your own client credentials), experiment with the OAuth 2.0 Playground.
Refer – https://developers.google.com/identity/protocols/OAuth2
Simply- your are the owner of your website and you have all admin privileges, ‘Guest’ want to access your page and surf some stuff unless admin grants him with some additional permissions . you can give some permission relevant to ‘Guest’ Role without sharing your identity and full privileges. This is exactly done by google OAuth, allow users to Authorize our page with some privileges.
Let start Coding part for Login System with Google using Php and OAuth Api, before that we need to Register our domain with goolge
Get CLIENT ID and SECRET KEY
Before Coding We need to get CLIENT ID and SECRET KEY for the google, because before the function we need register our website and get CLIENT ID and SECRET KEY for authentication and authorization to our website
Steps for Getting CLIENT ID and SECRET KEY
Step 1 – Go to the Url code.google.com/apis/console
It will redirect to gmail login page after you login with your goole account. It redirect to Google Developer console.
Note – This developer console is everyhting for create Apis Related to the Google
Step 2 – Create a New project with your project name
Step 3 – Click APIs & auth link and click credentials and Oauth 2.0 client Id
Step 4 – Before that create Contest screen for product and email verification
Step 5 – Select web Application and Enter you domain and redirect URL details and then get you credentials
Finally you get your CLIENT ID and SECRET KEY.
Coding Step
Create database and table
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Create config.php file for configuration with database.. enter Your CLIENT ID and SECRET KEY here and also domain redirect your.
<?php error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE); ob_start(); session_start(); define('PROJECT_NAME', 'Login System with Google using Php and OAuth Api - www.Developerdesks.com'); define('DB_DRIVER', 'mysql'); define('DB_SERVER', 'localhost'); define('DB_SERVER_USERNAME', 'root'); define('DB_SERVER_PASSWORD', ''); define('DB_DATABASE', 'google_login'); $dboptions = array( PDO::ATTR_PERSISTENT => FALSE, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', ); try { $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions); } catch (Exception $ex) { echo $ex->getMessage(); die; } /* make sure the url end with a trailing slash */ define("SITE_URL", "http://demos.developerdesks.com/login-with-google/"); /* the page where you will be redirected for authorzation */ define("REDIRECT_URL", SITE_URL."google_login.php"); /* * ***** Google related activities start ** */ define("CLIENT_ID", "your client ID"); /* Place you Clinet ID here */ define("CLIENT_SECRET", "your client secret"); /* Place you Clinet Secret code here */ /* 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")); /* * ***** Google related activities end ** */ ?>
Create redirect URL function google_login.php and this code for authentication the user with google whether he gave correct credentials or not. if give correct credentials check it ans success page redirect to specified page and insert user data into database. 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
<?php require('http.php'); // require for HTTp verification require('oauth_client.php'); // function for google Oauth integration require('config.php'); // require for domain and Client id and secret id verification $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('Please go to Google APIs console page ' . 'http://code.google.com/apis/console in the API access tab, ' . 'create a new client ID, and in the line ' . $application_line . ' set the client_id to Client ID and client_secret with Client Secret. ' . 'The callback URL must be ' . $client->redirect_uri . ' but make sure ' . 'the domain is valid and can be resolved by a public DNS.'); /* API permissions */ $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; if ($success) { // Now check if user exist with same email ID $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)"; /* Insert user data into database */ $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; ?>
finally create link for login in index.php
<div> <a href="google_login.php">Login with Google </a> </div>
Create welcome page with logout button in home.php
<div> <?php if ($_SESSION["e_msg"] <> "") { ?> <p><?php echo $_SESSION["e_msg"]; ?></p> </div> <?php } ?> <?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 } ?> <div> <a href="<?php echo LOGOUT_URL; ?>"> Logout </a> </div> </div>
Create logout.php function
<?php session_start(); $_SESSION = array(); unset($_SESSION); session_destroy(); header("location:index.php"); ?>
That’s it Enjoy the code.