Login with Google in a PHP web app

Login with Google in a PHP web app

We all have used Google Login at some point of time whether in any android app or in any web app.

It is one of the easiest ways to onboard any user into your app. You just need a single click and with your Google account, the user can easily login or signup in your website.

In today's post, I'll be showing you how you can use Google Sign-in on your PHP website. All you need is Google API Credentialand Google API Client Library for PHP which you can install using composer.

Google API Credentials

We'll start by getting Google API keys and for this, you need a google account and I hope we all have one.

Now, go to the below URL and sign in there.

Google Cloud Platform

Here, you need to click on Create Project button. It'll ask you to enter a name for your project.

Enter any name for your project and click Create.

Now go to the homepage of Google Console and from the menu on your left side of the screen, click on OAuth consent screen. Make sure your project is selected which you have created just now.

Give your application a name and click save. It will redirect to a new page and it will ask you to Create Credentials.

Click on that and select OAuth client ID from the dropdown.

It will ask you for application type. Select Web application and hit Create.

Give it a name and a redirect URL.

Enter the below URL in place of redirect URL. Here php-google-signin is the name of my project.

http://localhost/php-google-signin/index.php

All done. It will provide you with your client id and client secret key.

You are now done with the Google API Credentials part.

Let us now install google-api-package with the help of composer.

If you don't have composer installed in your machine, you can download it from here.

Composer

Once downloaded, install the required package by typing the following command from your terminal.

composer require google/apiclient:"^2.7"

Once the package is installed inside your project folder, we can now move on with the config.php page.

Inside your config.php page, place the below code and you just need to replace two lines of code with your google's client id and client secret key.

<?php  

// include google client library for php autoload file
require_once 'vendor/autoload.php';

// make object of google API client
$google_client = new Google_Client();

// set google oauth client ID

// enter your client id here inside the quotes
$google_client->setClientId('your-client-id-here-apps.googleusercontent.com');

// set google OAuth client secret key

// enter your client secret key here inside the quotes
$google_client->setClientSecret('your-client-secret-key-here');

// set google oauth redirect uri
$google_client->setRedirectUri('http://localhost/php-learning/index.php');

// to get email and profile
$google_client->addScope('email');
$google_client->addScope('profile');

// start session on web page
session_start();

?>

On line number 12, enter you client id which you copied from google.

// enter client id inside the quotes
$google_client->setClientId('');

On line number 17, enter your client secret.

// client secret key inside the quotes
$google_client->setClientSecret('');

You are done with the config.php file and we can now move on to index.php.

Inside your index.php file, paste the following code.

<?php  

include 'config.php';

$login_btn = '';

if (isset($_GET['code'])) {

    // fetching the token
    $token = $google_client->fetchAccessTokenWithAuthCode($_GET['code']);

    // check for any error while 
    if (!isset($token['error'])) {

        // set access token used for requests
        $google_client->setAccessToken($token['access_token']);


        // store access token in session for future use
        $_SESSION['access_token'] = $token['access_token'];

        // create object of google service oauth2 class
        $google_service = new Google_Service_Oauth2($google_client);

        // get user profile data from google
        $data = $google_service->userinfo->get();

        // find profile data and store it in session variable
        if (!empty($data['given_name'])) {
            $_SESSION['fname'] = $data['given_name'];
        }

        // fetch the first name and store it in the session variable
        if (!empty($data['family_name'])) {
            $_SESSION['lname'] = $data['family_name'];
        }

        if (!empty($data['email'])) {
            $_SESSION['email'] = $data['email'];
        }

        if (!empty($data['picture'])) {
            $_SESSION['picture'] = $data['picture'];
        }

    }

}

// check of the user is logged in using google account.
if (!isset($_SESSION['access_token'])) {
    $login_btn = '<a href="'.$google_client->createAuthUrl().'">Login with Google</a>';
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Google Login</title>
</head>
<body>

    <?php if ($login_btn == '') {

        // if login btn is a blank string, it means we have the auth token

    ?>

    <div>
        <h1>Welcome to Google Profile</h1>
        <p>Name: <?php echo $_SESSION['fname']; ?></p>
        <p>Email: <?php echo $_SESSION['email']; ?></p>
        <img src="<?php echo $_SESSION['picture']; ?>">
        <a href="logout.php">Logout</a>
    </div>


    <?php } else { ?>

        <!-- we don't have the auth token, we need to login the user -->
        <div>
            <?php echo($login_btn); ?>
        </div>

    <?php } ?>

</body>
</html>

I know this is not the best looking sign-in page but this post is not about CSS styling. If you want to style your index page, you can do by adding a stylesheet.

Now, we are done with the login part. If you want to test the link, open your browser and paste the link of your project index.php and it will ask you to login with google.

Use any of your Gmail and it will log you in and will show you your name, email and your profile picture.

Now we are left with the signout or the logout part. Below is the code for logout.php

<?php  

include ('config.php');

$accesstoken = $_SESSION['access_token'];

// reset oauth token
$google_client->revokeToken($accesstoken);

// destroy entire session data
session_destroy();

// redirect page to index.php
header('location:index.php');

?>

You are done with the PHP Google Sign in part. I hope you liked my post on login with Google in a PHP web app and if you found my post helpful, please share it with your friends and if you have any doubt, feel free to comment below.

Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!

Did you find this article valuable?

Support Learn Syntax by becoming a sponsor. Any amount is appreciated!