etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

PHP making secure Google oauth 2.0 login request and store logged user data in a MySQL Database

In this article, you will learn how to login with a Google account using Google oauth client api 2.0 using the PHP programming language. Most of the websites have sign in and sign up features. The manual registration of users increases the workload of both users and developers. The developer has to develop a secure registration system for users and users also invest time for registration.

Today, every professional has an account on Google, which helps them connect with the world's professionals. Google provides an api authentication protocol that allows third party websites to access a user's login. So, instead of providing registration on our website, why not use Google oauth service to login in our website.





These are the step-by-step process for making a secure Google oauth login request.


Create App and Get API Key and Secret Key

For developer security purposes, we need to generate a token that identifies both the application and the user. This token works as an ID when anyone tries to login through it. To get this token, go to the Google developer console API page.

Google API Console

  1. Either create a New Project or select your existing project.
  2. Select Credentials under the APIs & Services section. It is located in left side panel.
  3. Click on 'CREATE CREDENTIALS' drop down at the top and select OAuth Client ID.
  4. Select 'Web application' option under the Application Type.
  5. Enter redirect URL in the Authorized redirect URIs field.
  6. Click the create button.

PHP making secure Google oauth 2.0 login request



Install Google OAuth using Composer

If your system does not have installed composer, then first download the latest composer version from its official website -

https://getcomposer.org/download/

You can check a successful installation using the following command on cmd-

C:\>composer

The above command returns output like this-

PHP Install Composer

Now, go to your project directory on the command prompt and run the following command to install the Google oAuth library.

E:\>cd e:\wamp\www\oauth

E:\wamp\www\oauth>
E:\wamp\www\oauth>composer require google/apiclient:"^2.0"

After this, you have noticed that Composer has downloaded all libraries under the 'vendor' directory of your project root.



Create a Database

Let's create a database to store the logged in user information -

CREATE TABLE IF NOT EXISTS `user` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `id` varchar(100) NOT NULL,
  `email` varchar(100) DEFAULT NULL,
  `givenname` varchar(100) DEFAULT NULL,
  `familyname` varchar(100) DEFAULT NULL,
  `locale` varchar(50) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `picture` varchar(150) DEFAULT NULL,
  `verifiedEmail` int(11) DEFAULT NULL,
  `is_enable` int(11) NOT NULL,
  PRIMARY KEY (`sid`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;


Google oauth php

index.php

Here is the main PHP file, that we will call in the browser. At the top of this page, we have included the Google Oauth library file and provided a login link. Make sure to replace the Google configurations with yours.

<?php
require_once 'vendor/autoload.php';
 
// Initial Google Configuration
$clientID = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET_ID';
$redirectUri = 'YOUR_REDIRECT_URL';
  
// create Client Request to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
 
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
?>




googleoauth.php

Here is the redirect page that we have set in 'Authorized redirect URLs'. We have collected the user's data after successful login and stored in 'user' table.

<?php
require_once 'vendor/autoload.php';
 
// Initial Google Configuration
$clientID = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET_ID';
$redirectUri = 'YOUR_REDIRECT_URL';
  
// Create Google Client Request
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);

// Database Credentials
$hostname = "localhost";
$username = "root";
$password = "";
$database = "social";
 

$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);

//Get profile infomation
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
// Store in an array
$info = array($google_account_info['id'], $google_account_info['email'],
			$google_account_info['givenName'],$google_account_info['familyName'],
			$google_account_info['locale'],$google_account_info['name'],
			$google_account_info['picture'],$google_account_info['verifiedEmail']) ;
			
// Make Database Connection			
$conn = new mysqli($hostname, $username, $password, $database);
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
// Insert Data
$insert = "INSERT INTO user (`id`,`email`,`givenname`,`familyname`,`locale`,`name`,
		`picture`,`verifiedEmail`,`is_enable`) VALUES 
		(".$info[0].",'".$info[1]."','".$info[2]."','".$info[3]."','".$info[4]."',
		'".$info[5]."','".$info[6]."','".$info[7]."',1)";
if($conn->query($insert)){
 echo 'Data inserted successfully';
}
else{
 echo 'Error '.$conn->error;  
}
?>




Related Articles

Create Dynamic Pie Chart using Google API, PHP and MySQL
Google Street View API Example
Add google reCAPTCHA v2 in registration form using PHP
PHP remove HTML and PHP tags from string
Add multiple custom markers on google map
How to convert text to speech using PHP
Get current visitor's location using HTML5 Geolocation API and PHP
PHP String Contains
Retrieve Emails from Gmail using PHP IMAP
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Standard Library
File upload in PHP MySQL database
Send HTML form data to email using PHP
Forgot password code in PHP mysqli
PHP form validation example
Ajax submit form without reloading page
PHP form validation example
PHP Emojis in subject and body lines
PHP 7.3 new features
Insert in database without page refresh PHP




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
How to encrypt password in PHP
-----------------
Characteristics of a Good Computer Program
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to generate QR Code in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple way to send SMTP mail using Node.js
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Simple PHP File Cache
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
To check whether a year is a leap year or not in php
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
PHP Sending HTML form data to an Email
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.