How To Login With Google Using Php

How To Login With Google Using Php

How To Login With Google Using Php

0 Sales

Free

The Google OAuth API provides a powerful and easy way to integrate the website login system. The Google Login API enables users to sign up to the website using their Google account without signing up to the website. Google's login system definitely helps boost your website's subscribers. Because nowadays, nearly all users have a Google account and without registration on your website, they can log in with their Google account.

 

Using Google OAuth 2.0 and PHP, web developers can easily implement the web application's login and registration system. In this tutorial, we will show how you can use the Google API PHP library to integrate user login system with Google authentication. Here we will provide the step-by-step guide for Google Account login using PHP and store user information in the MySQL database. Using PHP in the web application, our example Google login script uses the API PHP client library to implement Google Login.

 

Take a look at the file structure before you start to integrate Login with Google using PHP and MySQL.

 

google_login_php/

├── config.php

├── index.php

├── logout.php

├── User.class.php

├── google-api-php-client/

├── css/

│   └── style.css

└── images/

    └── google-sign-in-btn.png


 

Create Google API Console Project

 

  1. Go to the console of the Google API.

  2. Select from the list of projects a current project, or select NEW PROJECT to create a new project: 

 

  • Enter the name of the project.

  • You will see the Google API console automatically generating a project ID under the Project Name. Optionally, the Edit link allows you to change this project ID. But the project identification must be unique throughout the world.

  • Click the CREATE button and in a few seconds the project will be created.

 

  1. Select Credentials in the APIs & Services section of the left side navigation panel.

  2. Select the screen of the OAuth consent tab and specify the settings of the consent screen.

 

  • In the area of the name of the application, enter the name of your application.

  • Pick an email address for client support in the Support email submitted.

  • Specify the domains that will be authorized to authenticate using OAuth in the Authorized domains.

  • Click the button Save.

 

  1. Select the Credentials tab, click Drop-down Credentials, and select OAuth Client ID. 


 

  • Select Web client in the Client Type page.

  • Enter the redirect URL in the Authorized redirect URIs area.

  • Click the button Build.

 

A dialog box with the details of the OAuth client will appear, note the secret of the client and client ID. This client ID and secret to the client enables you to access the Google APIs.

 

Create Database Table

A table must be built in the server to store user account information from Google. The following SQL generates a user table for keeping the Google profile information with some specific fields in the MySQL database.

 

CREATE TABLE `users` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

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

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

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

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

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

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

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

 `picture` varchar(255) COLLATE utf8_unicode_ci DEFAULT 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;


 

Google API Client Library for PHP

 

The directory of google-api-php-client/ contains PHP's Google OAuth Library. Installing the Google API PHP Client does not need the composer, it can be used without using the composer. You don't need to download it separately, all the appropriate Google API Library files are included in our Google Login PHP source code.

 

User Class (User.class.php)

The client class uses PHP and MySQL to manage the operations related to the server (connect, add, and update). This helps connect to the server and insert / update information from Google account in the table of users.

 

  • construct() –The MySQL server is connected.

  • CheckUser() –Upload or modify the OAuth Provider and ID-based user data. Returns a particular user's account data as an array.

 

<?php

/*

 * User Class

 * This class is used for database related (connect, insert, and update) operations

 * @author    CodexWorld.com

 * @url        http://www.codexworld.com

 * @license    http://www.codexworld.com/license

 */


class User {

    private $dbHost     = DB_HOST;

    private $dbUsername = DB_USERNAME;

    private $dbPassword = DB_PASSWORD;

    private $dbName     = DB_NAME;

    private $userTbl    = DB_USER_TBL;

    

    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 the database

            $checkQuery = "SELECT * FROM ".$this->userTbl." WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";

            $checkResult = $this->db->query($checkQuery);

            if($checkResult->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 = NOW() WHERE oauth_provider = '".$userData['oauth_provider']."' AND oauth_uid = '".$userData['oauth_uid']."'";

                $update = $this->db->query($query);

            }else{

                // Insert user data in the database

                $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 = NOW(), modified = NOW()";

                $insert = $this->db->query($query);

            }

            

            // Get user data from the database

            $result = $this->db->query($checkQuery);

            $userData = $result->fetch_assoc();

        }

        

        // Return user data

        return $userData;

    }

}




 

Site Settings and API Configuration (config.php)

 

Database settings and constant variables for the Google API configuration are specified in the config.php file.

Constants of the database: 

 

  • DB HOST–Specify the host for the database.

  • DB USERNAME–Enter the username of the server.

  • DB Code–Specify the code for the server.

  • DB NAME–Enter the name of the server.

  • DB USER TBL–Specify the name of the table that will store the account data of the user.

 

Google API constants: 

 

  • GOOGLE CLIENT ID–Specify Client ID for Google Project.

  • GOOGLE CLIENT SECRET–Specify Client Secret for Google Project.

  • GOOGLE REDIRECT URL–The callback URL is defined.

 

Call Google API:

The Google Client library is used to bind and work with the OAuth client with the Google API.

<?php

/*

 * Basic Site Settings and API Configuration

 */


// Database configuration

define('DB_HOST', 'MySQL_Database_Host');

define('DB_USERNAME', 'MySQL_Database_Username');

define('DB_PASSWORD', 'MySQL_Database_Password');

define('DB_NAME', 'MySQL_Database_Name');

define('DB_USER_TBL', 'users');


// Google API configuration

define('GOOGLE_CLIENT_ID', 'Insert_Google_Client_ID');

define('GOOGLE_CLIENT_SECRET', 'Insert_Google_Client_Secret');

define('GOOGLE_REDIRECT_URL', 'Callback_URL');


// Start session

if(!session_id()){

    session_start();

}


// Include Google API client library

require_once 'google-api-php-client/Google_Client.php';

require_once 'google-api-php-client/contrib/Google_Oauth2Service.php';


// Call Google API

$gClient = new Google_Client();

$gClient->setApplicationName('Login to CodexWorld.com');

$gClient->setClientId(GOOGLE_CLIENT_ID);

$gClient->setClientSecret(GOOGLE_CLIENT_SECRET);

$gClient->setRedirectUri(GOOGLE_REDIRECT_URL);


$google_oauthV2 = new Google_Oauth2Service($gClient);




 

Login & Get Google Account Data (index.php)

 

In this file, PHP is used to manage the authentication and authorization process of the API.

 

  1. Initially, the login URL for authentication will be created and the user will be shown the Google Sign-in key.

  2. If the user authenticates to their Google account, the following will happen: 

 

  • The data about the profile will be obtained from the Google account.

  • Using the user class checkUser() function, the account data is inserted into the server.

  • The account information of the user is stored in the SESSION.

  • The webpage displays the Google account information (name, email, gender, locale, profile image, and profile link).

<?php

// Include configuration file

require_once 'config.php';


// Include User library file

require_once 'User.class.php';


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

    $gClient->authenticate($_GET['code']);

    $_SESSION['token'] = $gClient->getAccessToken();

    header('Location: ' . filter_var(GOOGLE_REDIRECT_URL, 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();

    

    // Getting user profile info

    $gpUserData = array();

    $gpUserData['oauth_uid']  = !empty($gpUserProfile['id'])?$gpUserProfile['id']:'';

    $gpUserData['first_name'] = !empty($gpUserProfile['given_name'])?$gpUserProfile['given_name']:'';

    $gpUserData['last_name']  = !empty($gpUserProfile['family_name'])?$gpUserProfile['family_name']:'';

    $gpUserData['email']      = !empty($gpUserProfile['email'])?$gpUserProfile['email']:'';

    $gpUserData['gender']     = !empty($gpUserProfile['gender'])?$gpUserProfile['gender']:'';

    $gpUserData['locale']     = !empty($gpUserProfile['locale'])?$gpUserProfile['locale']:'';

    $gpUserData['picture']    = !empty($gpUserProfile['picture'])?$gpUserProfile['picture']:'';

    $gpUserData['link']       = !empty($gpUserProfile['link'])?$gpUserProfile['link']:'';

    

    // Insert or update user data to the database

    $gpUserData['oauth_provider'] = 'google';

    $userData = $user->checkUser($gpUserData);

    

    // Storing user data in the session

    $_SESSION['userData'] = $userData;

    

    // Render user profile data

    if(!empty($userData)){

        $output  = '<h2>Google Account Details</h2>';

        $output .= '<div class="ac-data">';

        $output .= '<img src="'.$userData['picture'].'">';

        $output .= '<p><b>Google ID:</b> '.$userData['oauth_uid'].'</p>';

        $output .= '<p><b>Name:</b> '.$userData['first_name'].' '.$userData['last_name'].'</p>';

        $output .= '<p><b>Email:</b> '.$userData['email'].'</p>';

        $output .= '<p><b>Gender:</b> '.$userData['gender'].'</p>';

        $output .= '<p><b>Locale:</b> '.$userData['locale'].'</p>';

        $output .= '<p><b>Logged in with:</b> Google</p>';

        $output .= '<p><a href="'.$userData['link'].'" target="_blank">Click to visit Google+</a></p>';

        $output .= '<p>Logout from <a href="logout.php">Google</a></p>';

        $output .= '</div>';

    }else{

        $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';

    }

}else{

    // Get login url

    $authUrl = $gClient->createAuthUrl();

    

    // Render google login button

    $output = '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="images/google-sign-in-btn.png" alt=""/></a>';

}

?>


<div class="container">

    <!-- Display login button / Google profile information -->

    <?php echo $output; ?>

</div>


 

Logout (logout.php)

 

The logout.php file will be loaded if the client wishes to log out of their Google account.

 

  • Remove from the SESSION token and user data.

  • Reset the permission token of OAuth.

  • Delete all information from the session.

  • Switch the client back to the homepage.

 

<?php

// Include configuration file

require_once 'config.php';


// Remove token and user data from the session

unset($_SESSION['token']);

unset($_SESSION['userData']);


// Reset OAuth access token

$gClient->revokeToken();


// Destroy entire session data

session_destroy();


// Redirect to homepage

header("Location:index.php");

?>

 

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0