How to create Login with Google Account using PHP

13 min read

This is how to add google login in your Website

Google oAuth API provides an easy and powerful way to integrate login system on the website. The web developers can implement login and registration system in the web application using Google OAuth 2.0. Google login system helps to increase subscribers on your website. Because nowadays almost all users have a Google account and they can log in with their Google account without registration in your website.

In this tutorial, we’ll show you simple login system integration process with Google authentication using Google API PHP library. Here we’ll provide the step-by-step guide to implementing login with Google account using PHP and store the user information to the MySQL database. Using our Google login script you can easily implement Login with Google using PHP at your website.

Before you begin to integrate Login with Google using PHP and MySQL, take a look at the folders and files structure.

  • index.php
  • gpConfig.php
  • User.php
  • logout.php
  • src/
    • Google API, Google Client, Google Oauth and other libraries
  • images/

Google Project Creation

  • Go to the Google Developers Console
  • Select an existing project, or create a new project by clicking Create Project:
    • In the Project name field, type in a name for your new project.
    • In the Project ID field, the console has created project ID. Optionally you can type in a project ID for your project. But project ID must be unique worldwide.
    • Click on the Create button and the project to be created in some seconds. Once the project is created successfully, the project name would be appearing at the top of the left sidebar.
  • In the left sidebar, select APIs under the APIs & auth section. A list of Google APIs appears.
  • Find the Google API service and set its status to Enable.
  • In the sidebar, select Credentials under the APIs & auth section.
  • In the OAuth section of the page, select Create New Client ID.
    • Create Client ID dialog box would be appearing for choosing application type.
    • In the Application type section of the dialog, select Web application and click on the Configure consent screen button.
    • Choose Email address, enter the Product name and save the form.
    • In the Authorized JavaScript origins field, enter your app origin. If you want to allow your app to run on different protocols, domains, or subdomains, then you can enter multiple origins.
    • In the Authorized redirect URI field, enter the redirect URL.
    • Click on Create Client ID.
  • The Client ID for web application will be generated. Note the Client ID and Client secret for later use that will need to use to access the APIs.
    google-project-creation-client-id-for-web-application-by-codexworld

Are you want to get a detailed guide on Google project creation? Go through this tutorial to creating Google Developers Console Project.

Database Table Creation

To store the Google profile information, you need to create a database and a table. At first, create a database (like codexworld) and run the below SQL on the database. The following SQL creates a users table to the database for inserting the user profile information.

CREATE TABLE `users` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

 `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,

 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,

 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `created` datetime NOT NULL,

 `modified` datetime NOT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

User Class (User.php)

The User class helps to insert or update user data to the database using PHP and MySQL. In User.php file, you only need to specify your MySQL database credentials ($dbHost$dbUsername$dbPassword, and $dbName) and table name ($userTbl) where you want to store the user data of Google profile.

<?php
class User {
    private $dbHost     = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "";
    private $dbName     = "codexworld";
    private $userTbl    = 'users';
    
    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;
            }
        }
    }
    
    function checkUser($userData = array()){
        if(!empty($userData)){
            //Check whether user data already exists in database
            $prevQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
            $prevResult = $this->db->query($prevQuery);
            if($prevResult->num_rows > 0){
                //Update user data if already exists
                $query = "UPDATE ".$this->userTbl." SET first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";
                $update = $this->db->query($query);
            }else{
                //Insert user data
                $query = "INSERT INTO ".$this->userTbl." SET oauth_provider = '".$userData['oauth_provider']."', oauth_uid = '".$userData['oauth_uid']."', first_name = '".$userData['first_name']."', last_name = '".$userData['last_name']."', email = '".$userData['email']."', gender = '".$userData['gender']."', locale = '".$userData['locale']."', picture = '".$userData['picture']."', link = '".$userData['link']."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
                $insert = $this->db->query($query);
            }
            
            //Get user data from the database
            $result = $this->db->query($prevQuery);
            $userData = $result->fetch_assoc();
        }
        
        //Return user data
        return $userData;
    }
}
?>

Google API Configuration (gpConfig.php)

In gpConfig.php file, define Google Project Client ID ($clientId), Client Secret ($clientSecret), and Callback URL ($redirectURL).

<?php
session_start();

//Include Google client library 
include_once 'src/Google_Client.php';
include_once 'src/contrib/Google_Oauth2Service.php';

/*
 * Configuration and setup Google API
 */
$clientId = 'InsertGoogleClientID';
$clientSecret = 'InsertGoogleClientSecret';
$redirectURL = 'http://localhost/login_with_google_using_php/';

//Call Google API
$gClient = new Google_Client();
$gClient->setApplicationName('Login to CodexWorld.com');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectURL);

$google_oauthV2 = new Google_Oauth2Service($gClient);
?>

Note that: You’ll find the Client ID and Client Secret on your Google API Manager page.

Login & Get Google Profile Data (index.php)

Initially, the Sign in with Google button will be shown. Once the user authenticates with their Google account, Google plus profile information will be fetched and pass to the User class for inserting into the database. Also, the profile details with logout button will be displayed.

<?php
//Include GP config file && User class
include_once 'gpConfig.php';
include_once 'User.php';

if(isset($_GET['code'])){
    $gClient->authenticate($_GET['code']);
    $_SESSION['token'] = $gClient->getAccessToken();
    header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
    $gClient->setAccessToken($_SESSION['token']);
}

if ($gClient->getAccessToken()) {
    //Get user profile data from google
    $gpUserProfile = $google_oauthV2->userinfo->get();
    
    //Initialize User class
    $user = new User();
    
    //Insert or update user data to the database
    $gpUserData = array(
        'oauth_provider'=> 'google',
        'oauth_uid'     => $gpUserProfile['id'],
        'first_name'    => $gpUserProfile['given_name'],
        'last_name'     => $gpUserProfile['family_name'],
        'email'         => $gpUserProfile['email'],
        'gender'        => $gpUserProfile['gender'],
        'locale'        => $gpUserProfile['locale'],
        'picture'       => $gpUserProfile['picture'],
        'link'          => $gpUserProfile['link']
    );
    $userData = $user->checkUser($gpUserData);
    
    //Storing user data into session
    $_SESSION['userData'] = $userData;
    
    //Render facebook profile data
    if(!empty($userData)){
        $output = '<h1>Google Profile Details </h1>';
        $output .= '<img src="'.$userData['picture'].'" width="300" height="220">';
        $output .= '<br/>Google ID : ' . $userData['oauth_uid'];
        $output .= '<br/>Name : ' . $userData['first_name'].' '.$userData['last_name'];
        $output .= '<br/>Email : ' . $userData['email'];
        $output .= '<br/>Gender : ' . $userData['gender'];
        $output .= '<br/>Locale : ' . $userData['locale'];
        $output .= '<br/>Logged in with : Google';
        $output .= '<br/><a href="'.$userData['link'].'" target="_blank">Click to Visit Google Page</a>';
        $output .= '<br/>Logout from <a href="logout.php">Google</a>'; 
    }else{
        $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }
} else {
    $authUrl = $gClient->createAuthUrl();
    $output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/glogin.png" alt=""/></a>';
}
?>

<div><?php echo $output; ?></div>

Logout (logout.php)

When the user wishes to logout from their account, the user would be redirected to this file.

<?php
//Include GP config file
include_once 'gpConfig.php';

//Unset token and user data from session
unset($_SESSION['token']);
unset($_SESSION['userData']);

//Reset OAuth access token
$gClient->revokeToken();

//Destroy entire session
session_destroy();

//Redirect to homepage
header("Location:index.php");
?>

Conclusion

We’ve tried to make Google login integration process simple as much as possible. Using our script, you can easily add login with Google system to your website. If you have any query or suggestions about this tutorial and scripts, feel free to comment here.

Total Execution Time content: 0.00041414896647135 Mins Total Execution Time social : 0.0001 Mins

Read Next

Total Execution Time red next: 0.0000 Mins

Search Now






Categories