
PHP Google OAuth API allows users to login in a website with their Google credentials. A user with a Google account need not remember yet another username/password for a web application. This PHP tutorial is to learn about setting up an authentication system for your custom web application using Google OAuth.
In an earlier tutorial, we have seen about Facebook OpenId authentication. Google OAuth is a bit easier than Facebook Authentication.
We are using Google OAuth Version 2.0 API.
Create a new project and get the corresponding OAuth credentials using Google developer console page.
Select APIS & AUTH –> APIs from Google project dashboard and enable Google+API.
Select APIS & AUTH –> credentials from the left menu.
Click Create new Client ID button and complete data on this wizard.
After submitting this form, we can get the client Id, secret key and etc as below,
Click Create New Key to create server key as Google project’s developer key. We should keep this key secure.
Finally, we have to design consent screen that will be shown on requesting user data.
Note: All the credentials we got from this step will be used later in our code for creating client request.
For setting the above credentials with our client authentication request, we need to download the Google AP Client Library from Github repository. After downloading, we should install it into the root directory. And then, we need to include the library source path using the php.ini file or by a dynamic function call.
include_path=".;C:\xampp\htdocs\phppot_samples\php_google_oauth_login\google-api-php-client\src"
ini_set('include_path', 'C:\xampp\htdocs\phppot_samples\php_google_oauth_login\google-api-php-client\src');
In this code, we need to include required OAuth service class to access Google API. And then, we have to start the session before sending any data to the browser. The code is,
<?php session_start(); require_once 'dbcontroller.php'; //Google API PHP Library includes require_once 'Google/Client.php'; require_once 'Google/Service/Oauth2.php'; // Fill CLIENT ID, CLIENT SECRET ID, REDIRECT URI from Google Developer Console $client_id = '<Your-Client-ID>'; $client_secret = '<Your-Client-Secret-Key>'; $redirect_uri = '<Callback-URL>'; $simple_api_key = '<Your-API-Key>'; //Create Client Request to access Google API $client = new Google_Client(); $client->setApplicationName("PHP Google OAuth Login Example"); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->setDeveloperKey($simple_api_key); $client->addScope("https://www.googleapis.com/auth/userinfo.email"); //Send Client Request $objOAuthService = new Google_Service_Oauth2($client); //Logout if (isset($_REQUEST['logout'])) { unset($_SESSION['access_token']); $client->revokeToken(); header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); //redirect user back to page } //Authenticate code from Google OAuth Flow //Add Access Token to Session if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); } //Set Access Token to make Request if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); } //Get User Data from Google Plus //If New, Insert to Database if ($client->getAccessToken()) { $userData = $objOAuthService->userinfo->get(); if(!empty($userData)) { $objDBController = new DBController(); $existing_member = $objDBController->getUserByOAuthId($userData->id); if(empty($existing_member)) { $objDBController->insertOAuthUser($userData); } } $_SESSION['access_token'] = $client->getAccessToken(); } else { $authUrl = $client->createAuthUrl(); } require_once("loginpageview.php") ?>
In the above code replace your own OAuth credentials and send it to Google OAuth Service class. Using this class instance we can access user data if the client access token is found. Otherwise, the login button will be shown which redirects to Google OAuth URL. The login view page code is,
<HTML> <HEAD> <style> .box {font-family: Arial, sans-serif;background-color: #F1F1F1;border:0;width:340px;webkit-box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.3);box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.3);margin: 0 auto 25px;text-align:center;padding:10px 0px;} .box img{padding: 10px 0px;} .box a{color: #427fed;cursor: pointer;text-decoration: none;} .heading {text-align:center;padding:10px;font-family: 'Open Sans', arial;color: #555;font-size: 18px;font-weight: 400;} .circle-image{width:100px;height:100px;-webkit-border-radius: 50%;border-radius: 50%;} .welcome{font-size: 16px;font-weight: bold;text-align: center;margin: 10px 0 0;min-height: 1em;} .oauthemail{font-size: 14px;} .logout{font-size: 13px;text-align: right;padding: 5px;margin: 20px 5px 0px 5px;border-top: #CCCCCC 1px solid;} .logout a{color:#8E009C;} </style> </HEAD> <BODY> <div class="heading">PHP Google OAuth 2.0 Login</div> <div class="box"> <div> <!-- Show Login if the OAuth Request URL is set --> <?php if (isset($authUrl)): ?> <img src="images/user.png" width="100px" size="100px" /><br/> <a class='login' href='<?php echo $authUrl; ?>'><img class='login' src="images/sign-in-with-google.png" width="250px" size="54px" /></a> <!-- Show User Profile otherwise--> <?php else: ?> <img class="circle-image" src="<?php echo $userData["picture"]; ?>" width="100px" size="100px" /><br/> <p class="welcome">Welcome <a href="<?php echo $userData["link"]; ?>" /><?php echo $userData["name"]; ?></a>.</p> <p class="oauthemail"><?php echo $userData["email"]; ?></p> <div class='logout'><a href='?logout'>Logout</a></div> <?php endif ?> </div> </div> </BODY> </HTML> </HTML>
While running user authentication code we can see,
By successful login, Google OAuth flow will redirect to the page we have specified.
PHP Google OAuth Login Source Code
I can’t download file
Hi Hassan,
There is a download link at the bottom of the article and it works.
Hello Vincy,
Super source
Thanks
Welcome Zafer.
Excellent work
Thank you Raj.
Nice
Thank you Abuu.