Implement social login with google in PHP

Login with username and password is kinda old school, now nobody wants to type a word. Everybody wants everything in one click, that’s why most websites have social logins like Google, Facebook etc..With this article I am starting a series of social logins. So let’s see how to implement social login with google in PHP.

Prerequisites

  • Google account
  • composer installed
  • PHP installed

Cool. If you dont have composer installed follow this articles help to get installed quickly. Choose your system Ubuntu , Windows .

First Google setup then Code

We are gonna need Google API and some credentials before we hit the code. So to begin with first, we have to create a project in google console by visiting the Google Developers console. It should open up the Dashboard page that looks like the below image.

Implement social login with google in PHP

Click on New project button

Click on the highlighted area. and it will open up a popup window like this.

Implement social login with google in PHP

Next Click on Create new project link in the right corner. you would see this screen . Enter the project name you like there is not any rules and select an organisation

Create new Project

Implement social login with google in PHP

Once you click on the Create button, you will be redirected back to the dashboard with a successful message.

Go in Oauth Consent screen

Now you are again dashboard so click on the Oauth Consent Screen in the left sidebar. The following screen will open up. Check the external because we want here to login by anyone who has a google account.

Once you clicked on Create button . New screen will open up like this.

Fill the required information in Oauth consent Screen

Well, you would be wondering, I didn’t fill all details. So that is because that detail is necessary when you will live your project currently we are working on the localhost. For now, only the application name is enough.

Go into the Credentials and select Ouath CLient ID

Next, click on Credentials in the left sidebar. That should show you the API Credentials but currently, we don’t have one, as shown in the following screenshot.

Next, Click on the Create Credentials on top and choose OAuth client ID. You will see the following screen.

Add required details and Click on Create

Redirect URI – http://localhost/Codekilla/google-login/redirect.php

Choose Application type as Web Application and then add name for Oauth authentication, finally add redirect URI. This URI should be your localhost URL where you will be redirected once you loggedin successfully.

Important step, Once you hit the Create button a pop up will appear with Client ID and Secret ID. Copy these two and save it we will gonna need these two in code.

Finally Its code time

As for now we have created project in google console with secret ID and Client ID , Now its time to use it.

I am going to use the composer to install the Google PHP Client SDK because it’s easy, hassle-free, and mainly CLI based.

To install the Google PHP SDK type the following command in your directory.

composer require google/apiclient

This command will create a vendor folder and composer.json and composer.lock, Although we don’t have to do anything in these files. We will create one new PHP file redirect.php and add the following code.

<?php
require_once 'vendor/autoload.php';
 
//google credntials
$clientID = '<YOUR_CLIENT_ID>';
$clientSecret = '<YOUR_CLIENT_SECRET>';
$redirectUri = '<REDIRECT_URI>';

// making a call to google_client
$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;
  $profile_pic =  $google_account_info->picture;
  echo "<h1>".$name."<br>".$email."</h1>";
  echo "<img src=".$profile_pic." width=100 height=100 alt=img-not-avaialable/>";
} else {
  echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?>

Time for some explanation, So in the first line require_once 'vendor/autoload.php';. We are instantiating Gooogle_Client. In the next lines, you have to add your credentials that earlier we created in Google console.

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

Now we have passed credentials, pass scopes which are nothing but the information we will receive after successful authentication. Below we are adding email and profile into the scope.

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

Next we have following code

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;
  $profile_pic =  $google_account_info->picture;
  echo "<h1>".$name."<br>".$email."</h1>";
  echo "<img src=".$profile_pic." width=100 height=100 alt=img-not-avaialable/>";
} else {
  echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}

else condition explanation

It has two blocks if and else. So by default, you will be else condition, which has Google Login text with an anchor tag. $client->createAuthUrl() will generate an authentication link based on previously we provided scopes and credentials. Once you click on Google Login it will take you to generated link and authorize and if you enter correct credentials it will redirect you back to REDIRECT URI with some parameter and token.

if condition explanation

As we see in else condition, once you authenticated you will redirect back with some parameter and token. These parameters will also have code parameter and that is our if condition. Redirect URL will look like this.

http://localhost/Codekilla/google-login/redirect.php?code=4%2F1gG-zgPx0AP8T5rW4pzW4jkQjF1pImx0LQ5aOb2O979q1OvSwM2a3qKrwdkgH07ZWeZXNhxXnnjope2AHE5dk9Y&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=3&prompt=consent#

As you can see in the first-line our URL and then code parameter with some random value and we have other parameters also.

Once we are inside if condition, we are using code value to fetch access_token. Then we are setting this access_token using $client->setAccessToken($token['access_token']);. Once the access token is set we are ready to fetch the required details.

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 I just displayed it right there you can save it in the database as other websites do.

So that’s all you need to know how to implement social login with google in PHP. Hope this article has helped you. If you have any queries let me know in the comment box

Leave a Reply

Your email address will not be published. Required fields are marked *