1. Code
  2. JavaScript
  3. Web APIs

Create a Google Login Page in PHP

Scroll to top

In this article, I’m going to explain how to integrate Google login in your PHP website. We’ll use the Google OAuth API, which is an easy and powerful way to add Google login to your site.

As a web user, you've probably experienced the hassle of managing different accounts for different sites—specifically, when you have several passwords for different services, and a website asks you to create yet another account on their site.

To deal with this, you could offer a single sign-on feature to allow visitors to use their existing credentials to open an account on your site. A lot of websites nowadays let users log in by using their existing accounts at Google, Facebook, or some other popular service. This is a convenient way for new users to register with a third-party site instead of signing up for a new account with yet another username and password.

In this post, we’ll use the Google OAuth login API, which allows users to log in with their existing Google accounts. Of course, users should still be able to register with the usual registration form on your site, but providing Google login or something like it can help maintain a healthy user retention ratio.

How Google Login Works

Let's quickly go through the top-level data flow of the whole process. As you can see in the following diagram, there are main three entities involved in the login process: the user, the third-party website, and Google.

Google Login data flowGoogle Login data flowGoogle Login data flow

Now, let’s understand the overall flow of how Google login works on your site.

On the login page of your site, there are two options users could choose from to log in. The first one is to provide a username and password if they already have an account with your site. And the other is to log in on your site with their existing Google account.

When they click on the Login With Google button, it initiates the Google login flow and takes users to the Google site for login. Once there, they log in with their Google credentials, and after that they will be redirected to the consent page.

On the consent page, users will be asked for permission to share their Google account information with the third-party site. In this case, the third-party site is a site where they want to use their Google account for login. They will be presented with two options: they can either allow or deny.

Once they allow their information to be shared with the third-party site, they will be taken back to the third-party site from where they initiated the Google login flow.

At this point, the user is logged in with Google, and the third-party site has access to the user profile information which can be used to create an account and do user login. So that’s the basic flow of integrating Google login on your site. The following diagram gives a quick overview of the steps that we've just discussed.

Google Login process flowGoogle Login process flowGoogle Login process flow

In the rest of the post, we’ll implement this login flow in a working example in PHP.

Setting Up the Project for Google Login

In this section, we’ll go through the basic setup which is required to integrate Google login with your PHP website.

Create a Google API Project

Firstly, you need to create an application with Google which will allow you to register your site with Google. It allows you to set up basic information about your website and a couple of technical details as well.

Once you’re logged in with Google, open the Google Developers console. That should open up the Google Dashboard page, as shown in the following screenshot.

DashboardDashboardDashboard

From the top-left menu, click on the Select a project link. That should open up a popup, as shown in the following screenshot.

New Project Pop UpNew Project Pop UpNew Project Pop Up

Click on the New Project link and it will ask you to enter the Project Name and other details. Fill in the necessary details, as shown in the following example.

Create New ProjectCreate New ProjectCreate New Project

Click on the Create button to save your new project. You will be redirected to the Dashboard page. Click on the Credentials from the left sidebar, and go to the OAuth consent screen tab.

oAuth Consent ScreenoAuth Consent ScreenoAuth Consent Screen

On this page, you need to enter the details about your application, like the application name, logo, and a few other details. Fill in the necessary details and save them. For testing purposes, just entering the application name should do it.

Next, click on Credentials in the left sidebar. That should show you the API Credentials box under the Credentials tab, as shown in the following screenshot.

Credentials TabCredentials TabCredentials Tab

Click Client credentials > OAuth client ID to create a new set of credentials for our application. That should present you with a screen that asks you to choose an appropriate option. In our case, select the Web application option and click on the Create button. You will be asked to provide a few more details about your application.

App SettingsApp SettingsApp Settings

Enter the details shown in the above screenshot and save it! Of course, you need to set the Redirect URI as per your application settings. It is the URL where the user will be redirected after login.

At this point, we’ve created the Google OAuth2 client application, and now we should be able to use this application to integrate Google login on our site. Please note down the Client ID and Client Secret values that will be required during the application configuration on our end. You can always find the Client ID and Client Secret when you edit your application.

Install the Google PHP SDK Client Library

In this section, we’ll see how to install the Google PHP API client library. There are two options you could choose from to install it:

  1. Use Composer.
  2. Download and install the library files manually.

The Composer Way

If you prefer to install it using Composer, you just need to run the following command.

1
$composer require google/apiclient:"^2.0"

And that's it!

Download the Release

If you don’t want to use Composer, you could also download the latest stable release from the official API page.

In my example, I just used Composer.

If you’re following along, by now you should have configured your Google application and installed the Google PHP API client library. In the next and final section, we’ll see how to use this library on your PHP site.

Client Library Integration

Recall that while configuring the Google application, we had to provide the redirect URI in the application configuration, and we set it to redirect to https://localhost/redirect.php. Now it’s time to create the redirect.php file.

Go ahead and create the redirect.php with the following contents.

1
<?php
2
require_once 'vendor/autoload.php';
3
 
4
// init configuration

5
$clientID = '<YOUR_CLIENT_ID>';
6
$clientSecret = '<YOUR_CLIENT_SECRET>';
7
$redirectUri = '<REDIRECT_URI>';
8
  
9
// create Client Request to access Google API

10
$client = new Google_Client();
11
$client->setClientId($clientID);
12
$client->setClientSecret($clientSecret);
13
$client->setRedirectUri($redirectUri);
14
$client->addScope("email");
15
$client->addScope("profile");
16
 
17
// authenticate code from Google OAuth Flow

18
if (isset($_GET['code'])) {
19
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
20
  $client->setAccessToken($token['access_token']);
21
  
22
  // get profile info

23
  $google_oauth = new Google_Service_Oauth2($client);
24
  $google_account_info = $google_oauth->userinfo->get();
25
  $email =  $google_account_info->email;
26
  $name =  $google_account_info->name;
27
 
28
  // now you can use this profile info to create account in your website and make user logged in.

29
} else {
30
  echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
31
}
32
?>

Let’s go through the key parts of the code.

The first thing we need to do is to include the autoload.php file. This is part of Composer and ensures that the classes we use in our script are autoloaded.

1
require_once 'vendor/autoload.php';

Next, there’s a configuration section, which initializes the application configuration by setting up the necessary settings. Of course, you need to replace the placeholders with your corresponding values.

1
// init configuration

2
$clientID = '<YOUR_CLIENT_ID>';
3
$clientSecret = '<YOUR_CLIENT_SECRET>';
4
$redirectUri = '<REDIRECT_URI>';

The next section instantiates the Google_Client object, which will be used to perform various actions. Along with that, we’ve also initialized our application settings.

1
// create Client Request to access Google API

2
$client = new Google_Client();
3
$client->setClientId($clientID);
4
$client->setClientSecret($clientSecret);
5
$client->setRedirectUri($redirectUri);

Next, we’ve added email and profile scopes, so after login we have access to the basic profile information.

1
$client->addScope("email");
2
$client->addScope("profile");

Finally, we have a piece of code which does the login flow magic.

1
// authenticate code from Google OAuth Flow

2
if (isset($_GET['code'])) {
3
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
4
  $client->setAccessToken($token['access_token']);
5
  
6
  // get profile info

7
  $google_oauth = new Google_Service_Oauth2($client);
8
  $google_account_info = $google_oauth->userinfo->get();
9
  $email =  $google_account_info->email;
10
  $name =  $google_account_info->name;
11
 
12
  // now you can use this profile info to create account in your website and make user logged in.

13
} else {
14
  echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
15
}

Firstly, let’s go through the else part, which will be triggered when you access the script directly. It displays a link which takes the user to Google for login. It’s important to note that we’ve used the createAuthUrl method of the Google_Client to build the OAuth URL.

After clicking on the Google login link, users will be taken to the Google site for login. Once they log in, Google redirects users back to our site by passing the code query string variable. And that’s when the PHP code in the if block will be triggered. We’ll use the code to exchange the access token.

Once we have the access token, we can use the Google_Service_Oauth2 service to fetch the profile information of the logged-in user.

So in this way, you’ll have access to the profile information once the user logs in to the Google account. You can use this information to create accounts on your site, or you could store it in a session. Basically, it’s up to you how you use this information and respond to the fact that the user is logged in to your site.

Useful PHP Form Scripts

Today, we discussed how you could integrate Google login with your PHP website. It allows users to sign in with their existing Google accounts if they don’t want to create yet another account for your service.

If you're looking for PHP scripts that you can use right away, I recommend you visit the following posts, which summarize some excellent scripts that are available for a low cost.

Let me know in the comments below if you have any questions!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.