May 09, 2019
Login with Google OAuth in PHP
Filling out online registration forms can be very frustrating for users. Google and many other famous social networks provide login libraries for developers to let your website's user login using their platforms without filling out registration form. We will be using Google OAuth 2.0 create a Login with Google script.
First thing you need to do is go to Google API Console and create a new project. Give your project any name you want and click create. After you have created your project:
Now next phase is to create OAuth clientID for our web application.
Now before we start coding for our login script for those who will be using it on localhost first. You might need cacert.pem for ssl issuer verification. You can download the fresh cacert.pem from here. Place the cacert.pem file anywhere in your wamp directory and update below two lines in php.ini.
For the coding job we are going to need index.php,logout.php, config.php, constants.php, style.css. First download the latest release of Google API Client PHP Library v2.2.2 from here.
Using OAuth 2.0 for Web Server Applications
- Click on credentials on left side menu.
- Click on OAuth Consent Screen tab.
- Enter your application name and upload a logo if needed.
- Select your support email address.
- By default google will add three scopes, profile, email, and openid, you can add more scopes here.
- Add authorized domains.
- Add application homepage link.
- Add application privacy page link.
- Click save.
Now next phase is to create OAuth clientID for our web application.
- Click on credentials tab.
- Click on create credentials and select OAuth Client ID from menu.
- Select "Web Application" under Application Type.
- Give your application a name.
- Enter authorized redirect URIs. These redirects are actually the URIs users will be redircted to after they login using their google account.
Now before we start coding for our login script for those who will be using it on localhost first. You might need cacert.pem for ssl issuer verification. You can download the fresh cacert.pem from here. Place the cacert.pem file anywhere in your wamp directory and update below two lines in php.ini.
curl.cainfo ="path-to-file-directory/cacert.pem" openssl.capath="path-to-file-directory/cacert.pem"
For the coding job we are going to need index.php,logout.php, config.php, constants.php, style.css. First download the latest release of Google API Client PHP Library v2.2.2 from here.
constants.php
Contains the constant values required in our script.<?php define("BASE_URL","http://".$_SERVER['SERVER_NAME']."/"); define("APPLICATION_NAME","YOUR_APPLICATION_NAME"); define("CLIENT_ID","YOUR_CLIENT_ID"); define("CLIENT_SECRET","YOUR_CLIENT_SECRET"); ?>
config.php
Contains the code to create client object from google client library.<?php session_start(); include_once("google-api-php-client-2.2.2/vendor/autoload.php"); include_once("constants.php"); $client = new Google_Client(); $client->setApplicationName(APPLICATION_NAME); $client->setClientId(CLIENT_ID); $client->setClientSecret(CLIENT_SECRET); $client->setAccessType("offline"); $client->addScope('profile email'); $client->setRedirectUri(BASE_URL."login-with-google-oauth-in-php"); ?>
index.php
Contains the code to show login button and user information block if user is already logged in.<?php include_once("config.php"); if(isset($_SESSION["access_token"])){ $client->setAccessToken($_SESSION["access_token"]); $service = new Google_Service_Oauth2($client); $user_info = $service->userinfo->get(); /************************************************** * YOU CAN STORE USER INFORMATION TO DATABASE HERE **************************************************/ }else{ if(isset($_GET['code'])){ $client->authenticate($_GET['code']); $_SESSION["access_token"] = $client->getAccessToken(); header("location: ".BASE_URL."login-with-google-oauth-in-php"); exit; } } ?> <!DOCTYPE html> <html> <head> <title>Login with Google OAuth in PHP - Demo</title> <meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/> <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css' rel='stylesheet'/> <link rel="stylesheet" href="css/style.css" /> </head> <body> <div class="main-container section"> <?php if(isset($_SESSION["access_token"])){?> <h3>You are logged in as:</h3> <div class="user-container"> <div class="user-picture"> <img src="<?php echo $user_info["picture"];?>" /> </div> <div class="user-info"> <div><strong><?php echo $user_info["name"]?></strong></div> <div><small><?php echo $user_info["email"]?></small></div> <a href="logout.php">Logout</a> </div> </div> <?php ?> <?php }else{?> <a href="<?php echo $client->createAuthUrl()?>" class="btn-google">Login with Google</a> <?php } ?> </div> </body> </html>
Logout.php
Contains the code to logout user and unset the token.<?php include_once("config.php"); unset($_SESSION['access_token']); $client->revokeToken(); header("Location:".BASE_URL."login-with-google-oauth-in-php"); ?>
style.css
Contains the css styling for login button and user information block.*{ box-sizing: border-box; text-decoration: none; } html,body{ margin: 0px; padding: 0px; } body{ background: #f0f0f0; font: normal normal 14px Open Sans,Verdana, Arial; } .main-container{ max-width: 1024px; margin: 0px auto; } .section { padding: 15px; } .user-container:before, .user-container:after{ content: ''; display: table; } .user-container:after{ clear:both; } .user-container{ background: #fff; padding: 15px; max-width: 300px; box-shadow: 0 0 5px #666; } .user-picture{ max-width: 60px; float: left; } .user-picture img{ max-width: 100%; height: auto; display: block; border-radius: 100%; } .user-info{ height: 100%; padding-left: 75px; } .btn-google{ background-image: url(../images/google-icon.png); background-repeat: no-repeat; background-position: 10px; background-color: #fff; border: 1px solid #4081ED; color: #4081ED; display: inline-block; padding: 10px 10px 10px 45px; }References:
Using OAuth 2.0 for Web Server Applications