X

Login with Google Account Using PHP

In this tutorial “Login with Google Account Using PHP” we are going to learn about setting up an authentication system for your custom web application using Google OAuth PHP and save the data into MySQL database. Today social login has become most important part of a web application for login and registration process. Today most of the website using this feature. It is not only about the login and registration. Because it only allows the genuine user which verified by the google so there is no any chance for spam. PHP Google OAuth API allows users to log in to a website with their Google credentials. And give permission to access basic profile which is a name with email will be stored in the database.

Implementing Google Login system in any website is really very easy, the Google API Client Library help and enables us to work with many Google services like Google+, Google Drive, YouTube etc.

What is OAuth?

An OAuth server 2.0 implementation with authorization code flow consists of two endpoints, which our service makes available by HTTPS. The 1st endpoint is authorization endpoint, which is responsible for finding consent from users for data access. Authorization endpoint presents sign-in UI to our users that aren’t already login and records consent to requested access. The 2nd endpoint is token exchange endpoint, which is used to exchange the encrypted strings called tokens for different types of tokens. These tokens are passed to our service to access content.

Google OAuth API provides a simple and powerful way to integrate login system in our website. The web developers can easily implement login and registration system in any web application using Google OAuth 2.0. Google login system also helps to increase subscribers on your website.

In this tutorial, we’ll provide the step-by-step guide to implementing login with Google account using PHP and store the user information in the MySQL database.

Login and Process Page

To design our google login button we firstly need client id, the secret key from Google API,  go to Google API console, create an OAuth client for Web Application, next you will be presented with your Client ID and Secret, which will be required in the code below.

Follow The below steps

To get your client id

the secret key

Step-1

Open Google API console and click to select a product option.

 

 

Step-2

Create a new project so enter your project name and clicks to create.

Step-3

Now select your project and click to open.

Step-4

Clicks to credential option to create the client id and security key.

Step-5

Now submit your details for OAuth consent Screen to create credential.

Step-6
Click on OAuth client ID

Step-7

Click to web application  then fill all details and  click to create

Step-8

Now you will get your client id and client secret key

Creating Our Database

Firstly, we have to create a database to store the data, for creating database follow these steps:

  • Open phpMyAdmin
  • Select database icon and Create a new database with the name after that.
  • Create the table with the table name.
  • And then insert the details Or
  • After creating a database name, click the SQL and paste the following code.

Create Table

CREATE TABLE `google_users` (
  `google_id` int(12) NOT NULL,
  `clint_id` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `google_email` varchar(60) NOT NULL,
  `gender` varchar(255) NOT NULL,
  `picture_link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Connection Page

This is a connection page, mysqli_connect() function opens connection to the MySQL server .

config.php

<?php
	session_start();
	require_once "googleapi/vendor/autoload.php";
	$gClient = new Google_Client();
	$gClient->setClientId("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
	$gClient->setClientSecret("xxxxxxxxxxxxxxxxxxxxxx");
	$gClient->setApplicationName("techjunkgigs");
	$gClient->setRedirectUri("http://localhost/login/g-callback.php");
	$gClient->addScope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");	
	$con = new mysqli('localhost', 'root','' ,'table');
    if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
}	
?>

Here you have to enter your own client id, client secret key, and other details.

Login Page

login.php

<?php
    require_once "config.php";
	if (isset($_SESSION['access_token'])) {
		header('Location: index.php');
		exit();
	}
	$loginURL = $gClient->createAuthUrl();
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0,">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px">
    <div class="row justify-content-center">
        <div class="col-md-6 col-offset-2" align="center">
		<h1>TechJunkGigs</h1>
		<h4>Login With Gmail</h4></br></br>
		<form>
		<input type="text" placeholder="Email" name="email" class="form-control"><br>
		<input type="password" placeholder="Password" name="password" class="form-control"><br>
		<input type="button" >

Logic page

g-callback.php

<?php
	require_once "config.php";
	if (isset($_SESSION['access_token']))
		$gClient->setAccessToken($_SESSION['access_token']);
	else if (isset($_GET['code'])) {
		$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
		$_SESSION['access_token'] = $token;
	} else {
		header('Location: login.php');
		exit();
	}
	$oAuth = new Google_Service_Oauth2($gClient);
	$userData = $oAuth->userinfo_v2_me->get();
	$_SESSION['id'] = $userData['id'];
	$_SESSION['email'] = $userData['email'];
	$_SESSION['gender'] = $userData['gender'];
	$_SESSION['picture'] = $userData['picture'];
	$_SESSION['familyName'] = $userData['familyName'];
	$_SESSION['givenName'] = $userData['givenName'];
 $sql="insert into google_users (clint_id,name,last_name,google_email,gender,picture_link) values
 ('".$userData['id']."','".$userData['givenName']."','".$userData['familyName']."','".$userData['email']."',
 '".$userData['gender']."','".$userData['picture']."')";
	mysqli_query($con,$sql);
	header('Location: index.php');
	exit();
?>

Mian Screen

Create a PHP file named “index.php” and paste the following code inside of it.

<?php
	session_start();
	if (!isset($_SESSION['access_token'])) {
		header('Location: login.php');
		exit();
	}
?>
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Login With Google</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px">
	<div class="row">
		<div class="col-md-3">
			<img style="width: 80%;" src="<?php echo $_SESSION['picture'] ?>">
		</div>
		<div class="col-md-9">
			<table class="table table-hover table-bordered">
				<tbody>
					<tr>
						<td>ID</td>
						<td><?php echo $_SESSION['id'] ?></td>
					</tr>
					<tr>
						<td>First Name</td>
						<td><?php echo $_SESSION['givenName'] ?></td>
					</tr>
					<tr>
						<td>Last Name</td>
						<td><?php echo $_SESSION['familyName'] ?></td>
					</tr>
					<tr>
						<td>Email</td>
						<td><?php echo $_SESSION['email'] ?></td>
					</tr>
					<tr>
						<td>Gender</td>
						<td><?php echo $_SESSION['gender'] ?></td>
					</tr>
					<tr>
						<td>Logout</td>
						<td><a href="logout.php">Logout</a></td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
</body>
</html>

Logout Page

logout.php

<?php
	require_once "config.php";
	unset($_SESSION['access_token']);
	$gClient->revokeToken();
	session_destroy();
	header('Location: login.php');
	exit();
?>

Demo Image

You can also check

Simple Login Page Using PHP and MySQL

I hope this article helped you to know  “Login with Google Account Using PHP”.To get the latest news and updates follow us on twitter facebook, subscribe to our YouTube channel.  And If you have any query then please let us know by using the comment form.

 

Categories: API MySQL PHP
Abhishek Kumar:
Related Post