Login with Google Account using PHP


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 on 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 from the projects drop-down, or create a new project by clicking Create project (+):
    • Enter the Project name and click Create to proceed.
    • Under the Project name, you will see the Google API console has created project ID. Optionally you can change this project ID by the Edit link. But project ID must be unique worldwide.
    • Click on the Create button and the project will be created in some seconds.
  • Select the newly created project and enable the Google+ API service.
    • In the sidebar, select Library under the APIs & Services section.
    • Search for the Google+ API service in the API list and select Google+ API.
    • Click the ENABLE button to make Google+ API service enable.
  • In the sidebar, select Credentials under the APIs & Services section.
  • Select OAuth consent screen tab. Choose an Email address, enter the Product name and click save.
  • Select Credentials tab, click the Create credentials drop-down and select OAuth client ID.
  • In the Application type section, select Web application.
    • 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 URIs field, enter the redirect URL.
    • Click the Create button.
  • A dialog box will appear with OAuth client details, copy the Client ID and Client secret. This Client ID and Client secret allows you to access the Google APIs.

Note that: This Client ID and Client secret need to be specified in the script on Google API call. Also, the Authorized redirect URI needs to be matched with the redirect URL specified in the script.

Are you want to get a detailed guide on Google project creation? Go through this tutorial to creating Google API 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 semicolonworld) 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` (
 `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,
) 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.

class User {
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "";
$dbName     "semicolonworld";
$userTbl    'users';
// Connect to the database
$conn = new mysqli($this->dbHost$this->dbUsername$this->dbPassword$this->dbName);
"Failed to connect with MySQL: " $conn->connect_error);
$this->db $conn;
checkUser($userData = array()){
//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);
$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);
//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).


//Include Google client library 
include_once 'src/Google_Client.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 semicolonworld.com');

$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.

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

$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' filter_var($redirectURLFILTER_SANITIZE_URL));

if (isset(
$_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
$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>'
$output '<h3 style="color:red">Some problem occurred, please try again.</h3>';
} else {
$authUrl $gClient->createAuthUrl();
$output '<a href="'.filter_var($authUrlFILTER_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.

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

//Unset token and user data from session

//Reset OAuth access token

//Destroy entire session

//Redirect to homepage

Related Articles

Comments 0