Integrating Google Sign-In into your website is recommended, as this gives users an easy way to login without remembering another password. You have to add the "Google Login" button in addition to a regular login with a username and password.
In this topic, we will develop a login screen with an option to login with a Google account along with login using a registered userid and password. We will use PHP and MySQL with HTML and CSS to develop this application.
You can also read this topic: How to display user name on header after login using PHP session
We will create a simple home page with a just Login Link. Login form will have both Google Login as well as registered user Login. For Google Login, we will use Google API and user can login with his/her Google account. If user logs in with registered email id and password, we will validate login details with data stored in database table. A major step will be to download Google API and create Google Client id and secret. With that, let us proceed with our development.
Google API
Since users will login with their Google account, we need to have a communication between Google and our application. This is done using Google API. Two things we need to do here:
- Download Google Client API Library
- Create Google Client id and Client Secret in Google's Developer Console
Download Google Client API Library
You need to have composer installed in your system before you download Google Client API library. Please follow below steps.
Set PHP path in your Computer and install Composer. If this is not done in your computer already, please follow below instructions:
If PHP path is not set, from your computer desktop right click on "This PC" (Windows 10) and click on properties. Fopr Windows 11, you can right click on Desktop and click on Display Settings. Then select System from left side and scroll down to click on About.
Click on advanced system settings and click on Environment variable.
Under System variables select Path and click on Edit.
Add your PHP installation folder by clicking on New, if it is not there already. For me it is D:\xampp\php so it shows as below:
Now, you need to install composer if it is not already installed. Composer is a tool which can manage the libraries you need to install/update for PHP. There are many websites available you can download composer from. It is quick and easy. Once composer is installed go to command prompt and type composer. If it is installed successfully, it will show options and commands available for composer as below. If you can see them, composer is installed in your system.
Once Composer is installed, you can download Google Client Library using Composer. It is very quick and easy to download using Composer.
Install Google API Client Library
Google provides a set of library files to integrate applications with Google Login and these are called Google API Client Libraries. You need to download Google API Client Libraries if you have not already downloaded it.
Go to your windows command prompt. Go to the desired folder where you want to install Google Client Library. For me, I have created a folder named 'google_login' in my XAMPP/htdocs. Then, I created a folder named 'Google_Api' under 'google_login'. Now go to windows command prompt and navigate to the desired folder. You can download it in any folder you want, you have to just note down the path and mention the path in the php program when you will use these libraries. Type below in command prompt and enter.
composer require google/apiclient:^2.0
It will start downloading the libraries. It may take some time to finish downloading. While download is in progress, you can start the next step below to create client id and client secret in Google.
Create Google client id and client secret keys from Google.
To use Google Client Libraries you need to have a client id and client secret key from Google. You must have a Google Account to get those values. I will describe how you can get those from Google Developers Console.
From browser open the URL https://console.developers.google.com/, login to your Google Account if it asks to login.
If you do not have any project already you will see "Select a Project", but if you have already one or more projects, you will see a default project is selected. You may or may not create a new project. But if you do not have a project already, you must create a project to get the client id and client secret.
Click on New Project and in the next screen give a project name. After entering Project name click on Create button.
This will create the project and new Screen will be displayed with the project name.
Make sure your project name is displayed as shown above. Now click on the OAuth Consent Screen from the left panel. And then select user Type as External and click on Create Button.
In the next screen under App Information, Enter App Name, your email id, optionally give a Logo of your website. Under App Domain, you can give the links as mentioned, these are not mandatory. Scroll down and under Developer contact information enter an email address and click on Save and Continue.
In the next screen just click on Save and Continue.
And again click on save and continue in the next screen.
After this, it displays the summary screen. Now click on Credentials from the left panel.
Click on Create Credentials and select OAuth Client Id.
In the next screen Select Application Type as Web Application and enter your Application Name.
Under Authorized redirect URIs click on Add URI button and enter the link of the webpage for the login redirect page. In our case it will http://localhost/google_login/login.php.
After entering redirect URI click on Create button. After this, oAuth client id will be created and will be displayed in a screen.
Copy Client id and Client Secret and save it somewhere. You will need them while developing login.php
program.
Creation of client id and client secret to use Google Api for Google Login are now completed. Just check if Google Client API libraries are installed by now succesfully.
I have kept everything including Google API library files in 'google_login' folder which is under my XAMMP/htdocs. We will use a folder named 'cfg' for Google config file.
Create a MySQL table
We will use a table named 'users' in MySQL database. This table will have user details. Table structure is given below:
- id - primary key and auto incremented
- email - email id of the user
- name - name of the user
- password - password for the user
- signup_date - date of signup, default is current date, this is used for information purpose only
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`signup_date` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `email`, `name`, `password`, `signup_date`) VALUES
(4, 'test@test.com', 'Test User', '202cb962ac59075b964b07152d234b70', '2021-10-13 00:00:00');
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Connect to MySQL database (dbconnect.php)
<?php
$server="localhost";
$userid="root";
$pwd="";
$dbname="demo";
$conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn)
die("Connection Error: " . mysqli_connect_error());
I am using mysqli_connect() function which needs 4 parameters.
- server - localhost
- userid - we will use root user
- password - no password for user root
- database name - demo in our case.
If connection is successful then it will return true and false otherwise. This Boolean value is returned and stored in the $conn variable. We will include this
dbconnect.php
in other php programs so that we do not need to write it again in the program. For detail database connection understanding please read topic
How to connect to MySQL database in PHP using MySQLi and PDO.
Create a config file for Google API (config.php)
We will create a config file to connect to Google API and use this config file in our login and logout page. So instead of writing the same code again and again, better approach is to create a single file and include in different places wherever you need. This config file will need google client library which we already downloaded and also it needs client id and client secret.
<?php
require_once 'google_api/vendor/autoload.php';
$clientID = 'xxxxxxx'; // replace with your actual client id
$clientSecret = 'xxxxxxx'; // replace with your actual client secret
$redirectUri = 'http://localhost/google_login/login.php';
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
In line 2, autoload.php
is included. we downloaded Google client library under xampp/htdocs/google_login/google_api. It is important that you use the path correctly. Redirect URI must match with what was given while creating oAuthId in Google Developer Console.
An instance of Google_client is created here and the basic information needed from Google are given in AddScope() method.
Create a Home Page (index.php)
We will not develop a complete home page as our main focus is on the login part of the application. You can use your own home page with all details we want to see in the home page.
We created header.php
as below, we will include this file in the home and Login page.
<?php
include "cfg/dbconnect.php";
if(!session_id()){
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="">
<title>Login with Google</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
Included db_connect.php
for database connection. Then started the PHP session. Code for home page is given below:
<?php
include 'header.php';
?>
<h1 style> You are at Home Page </h1>
<?php if (isset($_SESSION['email'])) {
echo "<h2>Welcome ".$_SESSION['name']."(".$_SESSION['email'].")</h2>";
?>
<h3><a href="logout.php">Logout </a></h3>
<?php }
else {
?>
<h3>Click <a href="login.php">here</a> to login</h3>
<?php } ?>
</body>
</html>
If the session variable is set, it means user is logged in so display the name and email id of the user and also display logout option. Otherwise, show login option.
Develop a Login form (login.php)
login.php
is the main program for Google login as well as for registered user login. Login screen will have both options - Login with Google and Login for registered users.
Overview of login.php
- It uses a simple form with a link for "Login with Google" and a Login form with email id and password to enter.
- User can choose either of the two options to login
- If user chooses "Login with Google", it will follow Google login using Google API. If login is successful, setup session variables and redirect user to home page with user name and email displayed on it.
- If user logs in as registered user, then check if email id and password are matching with values stored in database table, then setup session variables and redirect the user to home page with user name and email displayed on the home page. If login is not successful then remain in login page and display error message.
With this, let us look at the
login.php
program now:
<?php
include 'header.php';
include 'cfg/config.php';
$email = $name = $err_msg = "";
// authenticate code from Google
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$name = $google_account_info->name;
$email = $google_account_info->email;
$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['access_token'] = $token['access_token'];
header("location:index.php");
}
if (isset($_POST['submit'])) { // if Form is submitted
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$password = md5($password);
$sql = "select * from users where email = '$email' and password = '$password'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$_SESSION['name'] = $row['name'];
$_SESSION['email'] = $email;
header("location:index.php");
}
else
$err_msg = "Incorrect Email id/Password";
}
?>
<h1>Login</h1>
<form class="form-1" action="login.php" method ="post">
<div class="google-logo">
<a href="<?php echo $client->createAuthUrl();?>">
<img src="img/google.png" alt="google-login"/>
</a>
</div>
<p class="login">OR</p>
<?php if ($err_msg !="") ?>
<p class="err-msg"><?php echo $err_msg; $err_msg ="";?></p>
<div class="col-md-12 form-group">
<label>Email Id</label>
<input type = "text" class="form-control" name="email" id = "email" value="<?php echo $email;?>" placeholder ="Enter your Email Id" required>
</div>
<div class="col-md-12 form-group">
<label>Password</label>
<input type = "password" class="form-control" name="password" id = "password" placeholder ="Enter Password" required>
</div>
<div class="col-md-12 form-group text-right">
<button type="submit" class="btn btn-primary" name="submit">Login</button>
</div>
</form>
</body>
</html>
PHP code from line 6 to 34 are executed after the user submits the form. We will discuss this later.
An image of Google login with a link that calls Google client's createAuthUrl()
method is given in the form.
Google checks the redirect url which in our case is login.php
and controls go to line no 6. Google generates an access token and this token is used for the entire session while user is logged in using Google.
Now, to get the user details like name and email id, a google service is instantiated using new Google_Service_Oauth2($client)
. By calling the get()
method, we can get the user's email id and name.
Write Logout code (logout.php)
In logout.php
we have code to unset session variables and delete session.
<?php
include 'cfg/config.php';
session_start();
if (isset($_SESSION['access_token'])) {
$access_token = array();
$access_token['access_token'] = $_SESSION['access_token'];
$client->revokeToken($access_token);
unset($_SESSION['access_token']);
}
session_unset();
session_destroy();
header("location:index.php");
In case of Google login, we must check if access token is set in session then revoke the access token. session_unset()
will unset all session variables and session_destroy()
will delete the session. Then redirect the user to home page.
Add CSS (style.css)
Let us add below styles. We have included style.css
in header.php
already.
* {box-sizing: border-box;
}
body {
margin: 0;
font-family: Helvetica, sans-serif;;
}
h1,h2,h3{
text-align: center;
}
h2{
color:#1c47a9;
}
.err-msg{
text-align: center;
color:red;
}
.form-1 {
margin: 50px auto;
padding-bottom: 30px;
border: 1px solid #09168d;
border-radius: 7px;
background: #fff;
width: 37%;
}
label{
font-weight: bold;
}
.google-logo {
text-align: center;
}
img {
width:57%;
height:144px;
}
p{
text-align: center;
}
.login{
font-size: 23px;
color: #6c6666;
}