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 the Google login page and come back again to the application. In other words, 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, another option is to show the Google login popup within your application. The user will enter their credentials and on successful authentication logged in to your system.

In this article, we 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 which can be used throughout the application.

Get Google API Credentials

The integration of Google login into the website requires you to register the Google application. You can create 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 (+) 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 next steps.

Database Configuration

The login system requires a database to store the user information. Head over to the database and create the users table through the below SQL.

CREATE TABLE `users` (
 `google_uid` varchar(255) NOT NULL,
 `name` varchar(255) NOT NULL,
 `email` varchar(255) NOT NULL,
 `picture` text NOT NULL,

Next, create a database configuration file, say class-db.php. In this file, add the code for database connection, get user details, and insert/update the users.

class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
    public function __construct(){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
                die("Failed to connect with MySQL: " . $conn->connect_error);
                $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 = $arr_data['sub'];
        $name = $arr_data['name'];
        $email = $arr_data['email'];
        $picture = $arr_data['picture'];

        // check if user exists by fetching it's details
        $user = $this->get_user($uid);

        if(!$user) {
            // insert the user
            $this->db->query("INSERT INTO users(google_uid, name, email, picture) VALUES('$uid', '$name', '$email', '$picture')");
        } else {
            // update the user
            $this->db->query("UPDATE users SET name = '$name', email = '$email', picture = '$picture' WHERE google_uid = '$uid'");

Google Login using JavaScript

Following the Google documentation of JavaScript API, let’s build a Google login flow. Create a login.php file and add the code below to it.


// 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>
    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");
    window.onload = function () {
            client_id: "GOOGLE_CLIENT_ID",
            callback: handleCredentialResponse
            { theme: "outline", size: "large", width: "200" }  // customization attributes
        google.accounts.id.prompt(); // also display the One Tap dialog
<div id="buttonDiv"></div>

We have handled a couple of things in this file.

  • Using a PHP’s session, we restrict access of this file to only non logged in users. 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 to add Google login button and support for other configurations.
  • Initialize the process by passing Client ID and callback method.
  • Render the Google login button inside the div having a buttonDiv id. To the renderButton method, I have added a login button configuration – theme, size and width. 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, 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. At the click of this button, a login popup will open where users can add their Google account credentials. In the next step, we have to store the basic user details received after login.

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 the library using the command:

composer require google/apiclient

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


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

    // 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 send 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 and also the option to log out. Upon logout, the user will redirect to the login page.


// 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'])) {
    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>";


This tutorial will help you to integrate Google login popup into your application. It has shown you the flow of login with Google using JavaScript and PHP. Following this tutorial, your user can login with their Google account without leaving your application.

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

Leave a Reply

Your email address will not be published.