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.
-
PHP19 PHP Login and Registration Forms to Download
-
PHP20 Best PHP Email Forms
-
PHPCreate a Contact Form in PHP
-
PHPComparing the 5 Best PHP Form Builders (And 4 Free Scripts)
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, third party website and Google.
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.
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.
From the top left menu, click on the Select a project link. That should open up a popup as shown in the following screenshot.
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.
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.
On this page, you need to enter the details about your application like 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.
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.
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:
- Use Composer.
- 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.
$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 in 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.
<?php require_once 'vendor/autoload.php'; // init configuration $clientID = '<YOUR_CLIENT_ID>'; $clientSecret = '<YOUR_CLIENT_SECRET>'; $redirectUri = '<REDIRECT_URI>'; // create Client Request to access Google API $client = new Google_Client(); $client->setClientId($clientID); $client->setClientSecret($clientSecret); $client->setRedirectUri($redirectUri); $client->addScope("email"); $client->addScope("profile"); // authenticate code from Google OAuth Flow if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($token['access_token']); // get profile info $google_oauth = new Google_Service_Oauth2($client); $google_account_info = $google_oauth->userinfo->get(); $email = $google_account_info->email; $name = $google_account_info->name; // now you can use this profile info to create account in your website and make user logged in. } else { echo "<a href='".$client->createAuthUrl()."'>Google Login</a>"; } ?>
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.
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.
// init configuration $clientID = '<YOUR_CLIENT_ID>'; $clientSecret = '<YOUR_CLIENT_SECRET>'; $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.
// create Client Request to access Google API $client = new Google_Client(); $client->setClientId($clientID); $client->setClientSecret($clientSecret); $client->setRedirectUri($redirectUri);
Next, we’ve added email and profile scopes, so after login we have access to the basic profile information.
$client->addScope("email"); $client->addScope("profile");
Finally, we have a piece of code which does the login flow magic.
// authenticate code from Google OAuth Flow if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($token['access_token']); // get profile info $google_oauth = new Google_Service_Oauth2($client); $google_account_info = $google_oauth->userinfo->get(); $email = $google_account_info->email; $name = $google_account_info->name; // now you can use this profile info to create account in your website and make user logged in. } else { echo "<a href='".$client->createAuthUrl()."'>Google Login</a>"; }
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.
-
PHP19 PHP Login and Registration Forms to Download
-
PHP20 Best PHP Email Forms
-
PHPCreate a Contact Form in PHP
-
PHPComparing the 5 Best PHP Form Builders (And 4 Free Scripts)
Let me know in the comments below if you have any questions!
No comments:
Post a Comment