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 develop this application using PHP and MySQL with HTML and CSS.
You can also read the topic: How to Display User Name on Header after Login using PHP session
Let's see how we can implement this.
We will create a simple home page with a Login Link. The login form will have both Google Login and registered user Login. For Google Login, we will use Google API, and users can log in with his/her Google account. If the user logs in with a registered email id and password, we will validate login details with data stored in the database table. A major step is to download Google API and create a 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 communication between Google and our application. This is done using Google API. Two things we need to do here:
- Download the 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 the composer installed in your system before downloading the Google Client API library. Please follow the below steps.
Set the PHP path in your computer and install Composer. If this is not done on your computer already, please follow the below instructions:
If the PHP path is not set, right click on "This PC" and click on properties from your computer desktop. Then select System from the 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 the composer if it is not already installed. Composer is a tool that can manage the libraries you need to install/update for PHP. There are many websites available to download the composer. It is quick and easy. Once composer is installed go to command prompt and type composer. If installed successfully, it will show options and commands available for the composer as below. If you can see them, the composer is installed in your system.
Once Composer is installed, you can download the Google Client Library using Composer. It is very quick and easy to download.
Install Google API Client Library
Google provides a set of library files to integrate applications with Google Login, they 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. 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 the Windows command prompt and navigate to the desired folder. You can download it in any folder you want, you have to note down the path and mention the path in the PHP program when you will use these libraries. Type below in the 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 the download is in progress, you can start the next step below to create the 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 the 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 the Project name click on the Create button.
This will create the project and a 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 the Create Button.
In the next screen under App Information, enter your App Name, your email ID and 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 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 the "Application Type" as "Web Application" and enter your Application Name.
Under Authorized redirect URIs click on the Add URI button and enter the link of the login redirect page. In our case, it will be http://localhost/google_login/login.php.
After entering the redirect URI click on the Create button. After this, oAuth client ID will be created.
Copy the Client ID and Client Secret and save it somewhere. You will need them while developing login.php
program.
Creation of the client id and client secret to use Google API for Google Login is now completed. Just check if Google Client API libraries are installed now successfully.
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 the Google config file.
Create a MySQL table
We will use a table named 'users' in MySQL database. This table will have user details. The 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 purposes 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 with the below four parameters.
- server - localhost
- userid - we will use root user
- password - no password for the root user
- database name - demo in our case.
You can also read
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 repeatedly, a better approach is to create a single file and include it in different places wherever you need. This config file will need the Google client library which we already have downloaded and the 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 the Google client library under xampp/htdocs/google_login/google_api. You must use the path correctly. Redirect URI must match what was given while creating oAuthId in the Google Developer Console.
An instance of Google_client is created here and the basic information needed from Google is given in the 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 home page with all the details you want to see on the home page.
We created header.php
as below, we will include this file in the home and login pages.
<?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 the database connection. Then started the PHP session. The code for the 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 that the user is logged in, so display the name and email ID of the user and the logout option. Otherwise, show the login option.
Develop a Login form (login.php)
login.php
is the main program for Google login and registered user login. The 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 and password.
- Users can choose either of the two options to login
- If the user chooses "Login with Google", it will follow Google login using Google API. If login is successful, set up session variables and redirect the user to the home page with the user name and email displayed on the page.
- If the user logs in as a registered user, check if the email id and password match the values stored in the database table. Then set up session variables and redirect the user to the home page with the user name and email displayed on the home page. If login fails, remain on the login page and display the error message.
With this, let us look at the
login.php
program:
<?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 lines 6 to 34 is executed after the user submits the form. We will discuss this later.
An image of a Google login with a link that calls the Google client's createAuthUrl()
method is given in the form.
Google checks the redirect URL which in our case is login.php
and the control goes to line no 6. Google generates an access token used for the entire session while the user is logged in using Google.
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 the code to unset the session variables and delete the 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 the case of Google login, we must check if the access token is set in session and then revoke the access token. session_unset()
will unset all session variables and session_destroy()
will delete the session. Then redirect the user to the 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;
}
Test the Application
Before testing, make sure the services are running in the XAMPP control panel. Run localhost/google_login in the browser. You will see the home page displayed. Click on the Login link.
Test "Login with Google", you will see the Google Login page opens up as below:
Test "Login with Google", you will see Google Login page opens up as below:
Enter your Google account credentials and see if you can login using Google. If login is successful, the Home page will be displayed with your name and email id along with the Logout link.
Now, logout and login as a registered user with an email id and password. Enter the email id as 'test@test.com', the password as '123' and click the Login button. You will see the Home page with the Test user and the email id will be displayed on it.
Post a Comment