How to implement login with Google using PHP and MySQL

Integrating Google Sign-In into your website is required nowadays, 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.

Google Login in PHP

You can also read below topics:

  1. How to Develop a Login form with a Simple Menu in PHP and MySQL
  2. How to display user name on header after login using PHP session

We will create a simple home page with a just Login Link. When user clicks on Login link, a login page opens. 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 Account to sign inAssumption

  1. You must have basic knowledge of PHP, HTML, CSS and JavaScript/jQuery. You can read below topics for more details:
    1. How to install xampp for Windows with setup for PHP development
    2. How to write PHP code with examples for beginners
    3. How to build a simple CRUD application in PHP and MySQL

Authenticate Using Google with phpGoogle 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:
  1. Download Google Client API Library
  2. 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. I have tried to explain in details as much as possible.

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.

Google Social Connection to Login

Click on advanced system settings on the right side and click on Environment variable.

login with google button

Under System variables select Path and click on Edit.

Login with google account

Add your PHP installation folder, if it is not there already, by clicking on New. For me it is D:\xampp\php so it shows as below:

Login with google oauth

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.

implement sign in with google on my site

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 home. 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 where you will use these libraries. Type below in command prompt and enter.

composer require google/apiclient:^2.0

Install Composer

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.

Signing in with Google

Sign in with Google

Click on New Project and in the next screen give a project name. After entering Project name click on Create button.

Authenticating users with PHP

This will create the project and new Screen will be displayed with the project name.

adding Google login in PHP mysql

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.

Google Authentication in PHP

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.

Google social login guide

How to Login with Google in PHP

In the next screen just click on Save and Continue.

Login with Google Account using PHP

And again click on save and continue in the next screen.

make Login with Google Account using PHP

After this, it displays the summary screen. Now click on Credentials from the left panel.

Login with Google Account using PHP

Click on Create Credentials and select OAuth Client Id.

Create a Google Login Page in PHP

Login with Google Account Using PHP

In the next screen Select Application Type as Web Application and enter your Application Name.

PHP Google OAuth Login

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.

PHP MySQL Login with Google Account

Login with Google using PHP and MySQL

After entering redirect URI click on Create button. After this, oAuth client id will be created and will be displayed in a screen.

Login With Google Account on Website Using PHP MySQL

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.

Before going to Development Steps, let me show you the folders and files I am using for this application. Below is a screenshot of my folder structure and files:

google login development in PHP

I have kept everything including Google API library files in 'google_login' folder which is under my XAMMP home.

  1. Folder 'cfg' - In this folder I have kept Google config file and dbconnect.php which is used to connect to the MySQL database.
  2. Folder 'css' - My custom stylesheet is in this folder.
  3. Folder 'Googl_Api'- I have downloaded Google API files in this folder.
  4. Folder 'img' - This is where I keep all my image files for the application. In this case I kept an image used in login.php.
  5. header.php and index.php are the HTML header file and home page respectively. Header file is included in index.php, login.php and logout.php, I have written it once and used in other pages.

Step 1 - Create a MySQL table to store user details

Let us create a table named 'users' in MySQL database. This table will have user details. I have a database called 'demo'. If you have an existing database other than demo you can also use it. Just make sure same table name does not exist already. Table structure is given below:

Login with Google Account in PHP and MySQL

Table has 5 columns.

  1. id - it is the primary key and auto incremented
  2. email - email id of the user
  3. name - name of the user
  4. password - password for the user
  5. signup_date - date of signup, default is current date, this is not required for login, used as information purpose only
Create table script for this table is given below, you can use this code to create the table. Later in this topic, I have given a download button, by clicking the button you can download entire code for this application..

users.sql

After you create the table, please verify if data is inserted correctly, it should have below data in it, signup_date should be current date.

Login With Google Account Using PHP and MySQL

Step 2 - Connect to MySQL database (dbconnect.php)

Use below script to connect to the database. Note that we have this database connection php program in 'cfg' folder. This is written once and used in every program where database connection is needed. This will be easy for maintenance and also will enable reusability of the code.

dbconnect.php

I am using mysqli_connect() function which needs 4 parameters.

  1. server - in our case it is localhost
  2. userid - we are using root user
  3. password - no password for user root
  4. 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_connect.

Step 3 - Create a config file for Google API (config.php)

I 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 I already downloaded and also it needs client id and client secret. Let us look at the config file.

config.php

In line 2, autoload.php is included. I 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.

Step 4 - Create a Home Page (index.php)

I am not developing a complete home page as my 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 home page. My home page looks as below:

Home Page for Google Login in PHP

I created header.php as below, I will include this file in my home and Login page.

header.php

Included db_connect.php for database connection. Then started the PHP session. Code for home page is given below:

index.php

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.

Step 5 - Develop a Login form (login.php)

login.php is the main program for Google login as well as for registered user login. My login screen will have both options - Login with Google and Login for registered users. Below is the Login screen:

Google Login form in PHP

Overview of login.php

  1. It uses a simple form with a link for "Login with Google" and a Login form with email id and password to enter.
  2. User can choose either of the two options to login
  3. 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 id displayed on it.
  4. 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 id 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:

login.php

From line 6 to 34 are executed after user clicks on "Login with Google". I will discuss this little later.

An image of Google login with a link that calls Google client's createAuthUrl() method is given in the form.

Once user clicks on the Google link rest of the process is done by Google. 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.

Step 6 - Write Logout code (logout.php)

In logout.php we have code to unset session variables and delete session.

logout.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.

Step 7 - Add CSS (style.css)

Let us add below styles. I have included style.css in header.php already.

style.css

You can see simple styles are added here. Keep this style.css file in your css folder. You can always change the styles to make the screen design better.

Development is complete, let us test it now.

Login with Google using PHP tutorialTest the Application

Before testing, just make sure your services are running in XAMPP control panel. Open the browser and run localhost/google_login. You will see the home page displayed. Click on Login link.

Home page of Login with google in PHP

Login with Google Account using PHP

Now click "Login with Google", you will see Google Login page opens up as below:

How to Implement Google Login API in PHP

Enter your Google account credentials and see if you are able to login using Google. If successful login, Home page will be displayed with your name and email id along with Logout link.

Now, logout and login as a registered user with email id and password. Enter email id as 'test@test.com', password as '123' and click on Login button. You will see the Home page with Test user and email id displayed on it.

Login with Google using PHP API library

google login in php and mysqlImportant Note

Login with Google is a good choice for a web application. There are few things you must remember. While creating the App in OAuth Consent screen in Google developer console, you should give Application Logo, links for Home page, Privacy Policy and Terms of Service. This will help user to understand more about the website before login with Google.

Scope of Enhancement:

Put some contents in Home Page to make the home page look better. You might have to change position of Login, Logout and User name accordingly.

download source code for Google Login in PHPDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements. Note that, I have included Google API library files also in the zip file. But it is better to download them from Google to get the latest library files.

Integrating Google Sign-In into your websiteConclusion

In this topic I have showed you how you can develop login form with option for Google Login. It needs a lot of things to setup for Google Client. If you follow the steps, you will be able to understand clearly. Hope it will be useful for you to develop your own application.