Login with Google using JavaScript and PHP

In the past, I have written an article on Google Login integration with PHP. Following that article, when a user clicks on the login button they will redirect to Google’s website for login, and after completing the authentication they’ll redirect back to your website. During the login process, your users are away from your website for a while until they complete the Google authentication.

If you don’t want to redirect users to the Google login page then another option is to show the Google login popup within your application. The user will enter their credentials in the modal window and on successful authentication, log in to your system. It adds a better user experience to your login flow as everything happens in the modal window without leaving your website.

This kind of modal window can be implemented using JavaScript. And to log the user into your application you need a server-side language like PHP.

In this article, we study how to build a Google login popup using JavaScript and log the user in with the help of PHP. We also store the user details in the database that can be used in the application.

Get Google API Credentials

The integration of Google login into the website requires you to register the Google application. You can do it on Google Console and grab your client id. Below are the steps to follow.

  • Go to Google Developer Console.
  • Click on the drop-down and create a new project by clicking on the (+) sign. Alternatively, you can select the existing project also.
  • Select Credentials from the sidebar under APIs & Services.
  • Under the Credentials tab, click on the Create credentials drop-down and select OAuth client id.
  • In the OAuth Client settings, set Authorized JavaScript origins to the URL of the client application. In my case, I set it to http://localhost URL.
  • Once you save it, you will get the dialog box along with your Client ID and Client secret. Copy the Client ID which will be required in the next steps.
google-login-javascript

The purpose of this tutorial is to show Google login using JavaScript. So, it doesn’t require the client secret key. This key is only required when you integrate Google login with server-side language and without JavaScript.

Database Configuration

Whenever you integrate the login system, it requires a database to store the user information. This information you can utilize later in the application. Head over to the database and create the users table with the below SQL.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `google_uid` varchar(255) NOT NULL,
 `name` varchar(255) NOT NULL,
 `email` varchar(255) NOT NULL,
 `picture` text NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Next, create a database configuration file, say class-db.php. This file will be responsible for

  • Database connection
  • Fetch the user’s details
  • Insert or update the user’s information received after Google login
<?php
class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
 
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }

    public function get_user($id) {
        $sql = $this->db->query("SELECT * FROM users WHERE google_uid = '$id'");
        return $sql->fetch_assoc();
    }
 
    public function upsert_user($arr_data = array()) {
        $uid = $this->db->real_escape_string($arr_data['sub']);
        $name = $this->db->real_escape_string($arr_data['name']);
        $email = $this->db->real_escape_string($arr_data['email']);
        $picture = $this->db->real_escape_string($arr_data['picture']);
 
        // check if user exists by fetching it's details
        $user = $this->get_user($uid);
 
        if(!$user) {
            // insert the user
            $sql = sprintf("INSERT INTO users(google_uid, name, email, picture) VALUES('%s', '%s', '%s', '%s')", $uid, $name, $email, $picture);
            $this->db->query($sql);
        } else {
            // update the user
            $sql = sprintf("UPDATE users SET name = '%s', email = '%s', picture = '%s' WHERE google_uid = '%s'", $name, $email, $picture, $uid);
            $this->db->query($sql);
        }
    }
}

Google Login using JavaScript and PHP

Google provides in-depth documentation for the JavaScript API. With the help of these resources, we are going to build a Google login with JavaScript. It basically put a login button on your web page and provides different methods to handle the login journey of a user.

In order to build this flow, Create a login.php file and add the code below to it.

<?php
session_start();

// logged in user shouldn't access this page
if(isset($_SESSION['uid'])) {
    header('Location: profile.php');
}
?>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>
    function handleCredentialResponse(response) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if('success' == this.responseText) {
                    // redirect to profile page
                    location.href = 'DOMAIN_URL/profile.php';
                }
            }
        };
        xhttp.open("POST", "save-user.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("response="+response.credential);
    }
    window.onload = function () {
        google.accounts.id.initialize({
            client_id: "GOOGLE_CLIENT_ID",
            callback: handleCredentialResponse
        });
        google.accounts.id.renderButton(
            document.getElementById("buttonDiv"),
            { theme: "outline", size: "large", width: "200" }  // customization attributes
        );
        google.accounts.id.prompt(); // also display the One Tap dialog
    }
</script>
<div id="buttonDiv"></div>

There are a couple of things we have handled in this file.

  • Using a PHP session, we restrict access to this file to only users who haven’t logged in. The logged-in user will redirect automatically to the profile.php URL which we’ll create in a moment.
  • Include Google’s JS file https://accounts.google.com/gsi/client which adds a Google login button. This JS file also adds the other configurations required to initiate and handle the login flow.
  • Initialize the process by passing the Client ID and callback method.
  • Render the Google login button inside the div having the buttonDiv id. To the renderButton method, I have added a login button configuration – theme, size, and width. You may read more about the configuration on this link.
  • In the callback method, give an AJAX call to the save-user.php file providing the response(JWT token) received from Google.
  • Upon saving user information, redirect the user to the profile.php URL.

Make sure to replace placeholders DOMAIN_URL and GOOGLE_CLIENT_ID with their actual values.

At this stage, if you run the login.php on a browser, you will get a Google Login button. If you click this button, a login popup will appear where users can add their Google account credentials.

In the next step, you have to store the user’s information received after login and set the user’s session. This information has already been sent to the server-side script via Ajax. Let’s see how to receive these details and save them in the database.

Save User Information

From the login.php file, we have sent a JWT token to the save-user.php file. This JWT token needs to decode and simplify the response that contains user information. Google provides the apiclient library to decode this response. Install this library using the Composer command:

composer require google/apiclient

Next, in the save-user.php file, write the code as follows.

<?php
session_start();

require_once 'vendor/autoload.php';
require_once 'class-db.php';

$client_id = "GOOGLE_CLIENT_ID";
$id_token = $_POST['response'];
$client = new Google_Client(['client_id' => $client_id]);
$payload = $client->verifyIdToken($id_token); // verify JWT token received

if ($payload) {
    $db = new DB();

    // send user data to the database
    $db->upsert_user($payload);

    // set user id in session aka log in the user
    if(!isset($_SESSION['uid'])) {
        $_SESSION['uid'] = $payload['sub'];
    }

    echo 'success';
} else {
    echo 'Invalid Token';
}

Here, we decode and verify the response using a verifyIdToken() method. Then we grab the user details and pass them to the upsert_user() function of the DB class. Finally, we set the Google id of a user into the session variable. This variable identifies the user’s session and keeps them logged in to the system.

In the end, the profile.php file will have the code to fetch the user. It also has the option to log out the user. Upon logout, the user will redirect to the login.php URL.

<?php
session_start();

// non-logged in user shouldn't access this page
if(!isset($_SESSION['uid'])) {
    header('Location: login.php');
}

// log out the user and redirect to login page
if(isset($_GET['action']) && ('logout' == $_GET['action'])) {
    unset($_SESSION['uid']);
    header('Location: login.php');
}

require_once 'class-db.php';
$db = new DB();
$user = $db->get_user($_SESSION['uid']);

echo "Welcome ". $user['name'];
echo "<p><a href='profile.php?action=logout'>Log out</a></p>";

Conclusion

We have studied how to add Sign In with Google using JavaScript and PHP. As we are storing the users in the database, you can build the rest pages(like profile and user listing) based on these details. I hope this tutorial will help you to easily integrate the Google login popup into your application. Following this tutorial, your user can log in with their Google account without leaving your application.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “Login with Google using JavaScript and PHP

  1. Hey, this doesn’t seem to be working for me.

    1. I am missing the composer’s autoloader.php. I don’t know if it’s a necessary file, but I am not able to install it since I don’t have access to SSH on my webhosting.

    2. I seem to be getting loads of erros in class-db.php. More particularly on lines 9, 15, 21. I’m not sure if these are critical but they’re errors.

    3. I get an error “Uncaught Error: Class “Google_Client” not found in save-user.php on line 9″

Leave a Reply

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