w3tweaks.com
  • Effects
    • Scroll Effects
    • Text Effects
    • Shadow
  • Essentials
    • Arrows
    • Buttons
    • Background Patterns
    • Border Examples
    • Cards
    • Color Palettes
    • Dividers
    • Link styles
    • Loaders
    • Modal Windows
    • Notifications
    • Progress bar
    • Quote styles
    • Spinner
    • Tooltips
  • Media
    • Calendars
    • Carousels
    • Clocks
    • Gallery
    • Music Players
    • Sliders
    • Slideshows
    • Tables
    • Thumbnails
  • Navigation
  • Inputs
    • Range Sliders
    • Checkboxes
    • Toggle Switches
  • Script
    • Angularjs
    • Backbone.js
    • bootstrap
    • jQuery
    • ReactJs
    • JavaScript
    • Syntax Highlighters
    • tryit editor
    • PHP
  • API’s
    • Facebook
    • Google
    • Indeed
    • Twitter
    • YouTube
  • Tools
w3tweaks.com
Home API's

How to integrate the login using Google+ plus API in PHP

November 29, 2019
in API's, php

In the previous post we have already see how to integrate the LinkedIn Login with API and now make for Google+ API in PHP. Compare with LinkedIn Google is the best & everyone have a account in google all of they maintain simply in one account in google. That’s why peoples are like google.

Now we see how to make the Google OAuth in PHP. Actually the code is same for compare with LinkedIn OAtuth so you have easily understand this article.

You might also like

Retrieving a List of YouTube Videos by Channel

Send Email with PHPmailer

Securing PHP Login Scripts: Best Practices and Code Examples

Returning Dynamic Data in JSON Format using PHP: A Comprehensive Guide

13 Best PHP Login system

8 PHP Libraries for sending and parsing email

Google Developer Console

First, you need Client ID & Client Secret code to make the OAuth connection so here I have teach you how to get that just follow the steps here.

  1. Go to the Google Developer Console(https://console.developers.google.com/)
  2. Create new project & click create
  3. In the left sidebar Library tab will be visible, you have just click that and search Google+ API. Then click to Enable the Google+ API.
  4. Hereafter click Credentials.
  5. Click Create Credential tab button, Select Oauth Client ID
  6. Then list of Application type will be visible, you have just choose web application & create button.
  7. Then enter the Authorized Javascript Origins URL. The URL like http://www.w3tweaks.com
  8. Then fill the Authorized redirect URIs it like http://www.w3tweaks.com/googlelogin
  9. Finally click Save Button.

It’s like,

google developer console form

Database Configuration

Now move on the PHP code to integrate the Googel OAuth API. So first create one database the database name is googlelogin then just import the users.sql file in your database. Now the database side will be finished.

Integrate PHP code in Google+

So now open the gpConfig.php file and edit the following things like Client ID, Client Secret & redirect url. The code is

<?php
	session_start();

	//Include Google client library 
	include_once 'src/Google_Client.php';
	include_once 'src/contrib/Google_Oauth2Service.php';

	
	$clientId = '571949240375-trjeljafkbb39dnnqi98sfhg6cf7o0v3.apps.googleusercontent.com'; //Google client ID
	$clientSecret = 'PeQNr3CBhdZvaUXA0kQe5_ge'; //Google client secret
	$redirectURL = 'http://www.w3tweaks.com/demo/googlelogin'; //Callback URL

	//Call Google API
	$gClient = new Google_Client();
	$gClient->setApplicationName('Login to W3tweaks.com');
	$gClient->setClientId($clientId);
	$gClient->setClientSecret($clientSecret);
	$gClient->setRedirectUri($redirectURL);

	$google_oauthV2 = new Google_Oauth2Service($gClient);
?>

When you have change the Client ID & secret it will affect your code, so don’t change & delete. Suppose if you have delete just create another project and make the client ID’s to fetch the same credentials.

Homepage for Google+ OAuth

This is your own design, you have write any code to UI design to make the attractive look for your user. So just make the new things like attractive login page example. The sample code is,

<?php
    //Include GP config file && User class
    include_once 'gpConfig.php';
    include_once 'User.php';

    if(isset($_GET['code'])){
    	$gClient->authenticate($_GET['code']);
    	$_SESSION['token'] = $gClient->getAccessToken();
    	header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['token'])) {
    	$gClient->setAccessToken($_SESSION['token']);
    }

    if ($gClient->getAccessToken()) {
    	//Get user profile data from google
    	$gpUserProfile = $google_oauthV2->userinfo->get();
    	
    	//Initialize User class
    	$user = new User();
    	
    	//Insert or update user data to the database
        $gpUserData = array(
            'oauth_provider'=> 'google',
            'oauth_uid'     => $gpUserProfile['id'],
            'first_name'    => $gpUserProfile['given_name'],
            'last_name'     => $gpUserProfile['family_name'],
            'email'         => $gpUserProfile['email'],
            'gender'        => $gpUserProfile['gender'],
            'locale'        => $gpUserProfile['locale'],
            'picture'       => $gpUserProfile['picture'],
            'link'          => $gpUserProfile['link']
        );
        $userData = $user->checkUser($gpUserData);
    	
    	//Storing user data into session
    	$_SESSION['userData'] = $userData;
    	
    	//Render facebook profile data
        if(!empty($userData)){
            $output = '<h1>Google+ Profile Details </h1>';
            $output .= '<img src="'.$userData['picture'].'" width="300" height="220">';
            $output .= '<br/>Google ID : ' . $userData['oauth_uid'];
            $output .= '<br/>Name : ' . $userData['first_name'].' '.$userData['last_name'];
            $output .= '<br/>Email : ' . $userData['email'];
            $output .= '<br/>Gender : ' . $userData['gender'];
            $output .= '<br/>Locale : ' . $userData['locale'];
            $output .= '<br/>Logged in with : Google';
            $output .= '<br/><a href="'.$userData['link'].'" target="_blank">Click to Visit Google+ Page</a>';
            $output .= '<br/>Logout from <a href="logout.php">Google</a>'; 
        }else{
            $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
        }
    } else {
    	$authUrl = $gClient->createAuthUrl();
    	$output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/glogin.png" alt=""/></a>';
    }
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Login with Google using PHP by CodexWorld</title>
        <style type="text/css">
            h1{font-family:Arial, Helvetica, sans-serif;color:#999999;}
        </style>
    </head>
    <body>
        <div><?php echo $output; ?></div>
    </body>
</html>

Execute the Program

The exact output look like,

google+ plus confirmation

Login with Google using PHP

Over. If you have any doubt regarding this feel free to comment below.

Download Demo

Tags: APIgoogleloginoauthoAuth2phpplus
Previous Post

Login using LinkedIn oAuth2 in php and MySQL

Next Post

Re-sign an Android APK Manually for an application

Related Stories

Retrieving a List of YouTube Videos by Channel
API's

Retrieving a List of YouTube Videos by Channel

February 14, 2023
Send Email with PHPmailer
php

Send Email with PHPmailer

February 10, 2023
Securing PHP Login Scripts: Best Practices and Code Examples
php

Securing PHP Login Scripts: Best Practices and Code Examples

February 8, 2023
Returning Dynamic Data in JSON Format using PHP
php

Returning Dynamic Data in JSON Format using PHP: A Comprehensive Guide

February 8, 2023
PHP Login system
php

13 Best PHP Login system

February 8, 2023
Collection of PHP Libraries for sending and parsing email
Libraries

8 PHP Libraries for sending and parsing email

February 8, 2023
PHP Content Management Systems
CMS

8 PHP Content Management Systems (CMS)

February 8, 2023
Login the App using facebook oauth in PHP
API's

Login the App using facebook oauth in PHP

February 8, 2023

Discussion about this post

Follow Us

Popular Posts

100 Creative CSS Cards

44 Free Multi step HTML forms

13 Free HTML & CSS Dashboard Template Designs

49 CSS Tables

20 HTML & CSS pricing tables

14 Best CSS Dark Mode

11 CSS Shopping Cart UI/UX

42 Cool CSS Avatars For Better UI

55 Useful handpicked CSS Buttons with examples and demos

89 Best CSS Toggle Switches

w3tweaks

We bring you the best frontend collections that will fix perfect for news, magazine, personal blog, etc. Check our landing page for details.

  • Effects
    • Scroll Effects
    • Text Effects
    • Shadow
  • Essentials
    • Arrows
    • Buttons
    • Background Patterns
    • Border Examples
    • Cards
    • Color Palettes
    • Dividers
    • Link styles
    • Loaders
    • Modal Windows
    • Notifications
    • Progress bar
    • Quote styles
    • Spinner
    • Tooltips
  • Media
    • Calendars
    • Carousels
    • Clocks
    • Gallery
    • Music Players
    • Sliders
    • Slideshows
    • Tables
    • Thumbnails
  • Navigation
  • Inputs
    • Range Sliders
    • Checkboxes
    • Toggle Switches
  • Script
    • Angularjs
    • Backbone.js
    • bootstrap
    • jQuery
    • ReactJs
    • JavaScript
    • Syntax Highlighters
    • tryit editor
    • PHP
  • API’s
    • Facebook
    • Google
    • Indeed
    • Twitter
    • YouTube
  • Tools