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- Either create a New Project or select your existing project.
- Select Credentials under the APIs & Services section. It is located in left side panel.
- Click on 'CREATE CREDENTIALS' drop down at the top and select OAuth Client ID.
- Select 'Web application' option under the Application Type.
- Enter redirect URL in the Authorized redirect URIs field.
- Click the create button.

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-

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.phpHere 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 MySQLGoogle 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