Login with Google Account in CodeIgniter

Google OAuth API is the simple and powerful way to integrate the login system on the website. Google OAuth Login API lets you allow the user to sign in the web application using their Google account without registration. The main advantage of Google login is the user can log in to the web application with their existing Google account without register the account on the website. Nowadays almost all web users have a Google account, Sign-in with Google helps to increase the user’s subscription on your website.

Google API allows to authenticate with Google account and retrieve the user’s profile data. You can easily integrate login with Google API using PHP and Google OAuth library. If your web application built with CodeIgniter, Google API Client library needs to be integrated into the CodeIgniter application. In this tutorial, we will show you how to integrate Google login in CodeIgniter using Google API PHP client and allow the user to Sign In with Google in CodeIgniter.

In the example code, we will provide a step-by-step guide to implement Google login in CodeIgniter and get the Google profile information using Google API Client Library. Also, the user’s account data will be stored in the MySQL database.

Before you begin to implement Google login in CodeIgniter 3 using PHP Client Library, create a Project in Google API Console and generate the Client ID and Client secret.

Create Google API Console Project

  • Go to the Google API Console.
  • Select an existing project from the projects list, or click NEW PROJECT to create a new project:
    • Type the Project Name.
    • Under the Project Name, you will see the project ID is created by Google API console. You can edit and change this project ID by the Edit link. But the project ID must be unique worldwide.
    • Click the CREATE button, the project will be created in some seconds.
  • In the left side navigation bar, select Credentials under the APIs & Services section.
  • Select OAuth consent screen tab, settings up the consent screen.
    • Enter the Application name.
    • Choose an email address from Support email dropdown.
    • Specify the Authorized domains to allow the OAuth authentication.
    • Click the Save button.
  • Select the Credentials tab, click the Create credentials drop-down and select OAuth client ID.
    • Select Web application as the Application type.
    • Specify the redirect URL in the Authorized redirect URIs field.
    • Click the Create button.

A dialog window will appear with OAuth API credentials (Client ID and Client secret). Copy the Client ID and Client secret for later use in the script to access the Google APIs.

codeigniter-google-api-console-oauth-client-id-secret-codexworld

Before getting started to Google login integration process, take a look at the files structure of Login with Google in CodeIgniter.

codeigniter_google_login/
├── application/
│   ├── config/
│   │   └── google.php
│   ├── controllers/
│   │   └── User_authentication.php
│   ├── libraries/
│   │   └── Google.php
│   ├── models/
│   │   └── User.php
│   ├── third_party/
│   │   └── google-api-client/
│   ├── views/
│   │   ├── user_authentication/
│   │   │   ├── index.php
│   │   │   └── profile.php
└── assets/
    ├── css/
    └── images/

Create Database Table

To store the Google account information, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(50) 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;

Config (application/config/)

autoload.php
Specify the commonly used library (database and session) or helper (url) to load by default.

$autoload['libraries'] = array('database''session');

$autoload['helper'] = array('url');

google.php
Google API configuration variables are defined in this file. Specify the Client ID, Client Secret and Redirect URL according to the API credentials of your Google API Console Project.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------
|  Google API Configuration
| -------------------------------------------------------------------
| 
| To get API details you have to create a Google Project
| at Google API Console (https://console.developers.google.com)
| 
|  client_id         string   Your Google API Client ID.
|  client_secret     string   Your Google API Client secret.
|  redirect_uri      string   URL to redirect back to after login.
|  application_name  string   Your Google application name.
|  api_key           string   Developer key.
|  scopes            string   Specify scopes
*/
$config['google']['client_id']        = 'Google_API_Client_ID';
$config['google']['client_secret']    = 'Google_API_Client_Secret';
$config['google']['redirect_uri']     = 'https://example.com/project_folder_name/user_authentication/';
$config['google']['application_name'] = 'Login to CodexWorld.com';
$config['google']['api_key']          = '';
$config['google']['scopes']           = array();

Note that: You’ll find the Client ID and Client Secret at your Google API Console Project. (Go to the Google API Credentials page » Click on OAuth Client ID for Web application » Copy the Client ID and Client secret » Replace the client_id value with Client ID and client_secret value with Client secret)

Third Party (application/third_party/)

google-api-client/
Google API PHP client is used to connect and authenticate with Google OAuth API. The google-api-client library needs to be placed in the third_party/ directory of your CodeIgniter application.

Note that: You don’t need to download the Google API PHP client library separately, all the required files are included in the source code.

Libraries (application/libraries/)

Google.php
The Google OAuth library helps to integrate Google API client in CodeIgniter 3.x application. You can easily add the login with Google functionality to the CodeIgniter application using Google API PHP client library.

Note that: You don’t need to download it separately, the Google library file is included in the source code.

Controllers (application/controllers/)

User_authentication.php
The User_Authentication controller handles the authentication, Sign-in, and Sign out process with Google account.

  • __construct() – The Google library and User model are loaded in this method.
  • index() – This function handles the authentication functionality with Google account.
    If the user authenticated with Google, the following happens:

    • Connect and authenticate with Google OAuth API using the Google OAuth library.
    • Fetch the user’s profile info from Google account.
    • Insert Google account data in the database using checkUser() method of the User model.
    • Store login status token and user profile data into session.
    • Redirect the user to the profile page.

    For the non-authenticated user, Google authentication URL is generated and login view is loaded.

  • profile()
    • Retrieve the user data from the SESSION.
    • Load the profile view to display the Google profile info.
  • logout()
    • Reset the access token using the revokeToken() function of Google OAuth library.
    • Remove the user account data from the SESSION.
    • Log out the user from Google account.
<?php 
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
User_Authentication extends CI_Controller {
    
    function 
__construct(){
        
parent::__construct();
        
        
// Load google oauth library
        
$this->load->library('google');
        
        
// Load user model
        
$this->load->model('user');
    }
    
    public function 
index(){
        
// Redirect to profile page if the user already logged in
        
if($this->session->userdata('loggedIn') == true){
            
redirect('user_authentication/profile/');
        }
        
        if(isset(
$_GET['code'])){
            
            
// Authenticate user with google
            
if($this->google->getAuthenticate()){
            
                
// Get user info from google
                
$gpInfo $this->google->getUserInfo();
                
                
// Preparing data for database insertion
                
$userData['oauth_provider'] = 'google';
                
$userData['oauth_uid']         = $gpInfo['id'];
                
$userData['first_name']     = $gpInfo['given_name'];
                
$userData['last_name']         = $gpInfo['family_name'];
                
$userData['email']             = $gpInfo['email'];
                
$userData['gender']         = !empty($gpInfo['gender'])?$gpInfo['gender']:'';
                
$userData['locale']         = !empty($gpInfo['locale'])?$gpInfo['locale']:'';
                
$userData['picture']         = !empty($gpInfo['picture'])?$gpInfo['picture']:'';
                
                
// Insert or update user data to the database
                
$userID $this->user->checkUser($userData);
                
                
// Store the status and user profile info into session
                
$this->session->set_userdata('loggedIn'true);
                
$this->session->set_userdata('userData'$userData);
                
                
// Redirect to profile page
                
redirect('user_authentication/profile/');
            }
        } 
        
        
// Google authentication url
        
$data['loginURL'] = $this->google->loginURL();
        
        
// Load google login view
        
$this->load->view('user_authentication/index',$data);
    }
    
    public function 
profile(){
        
// Redirect to login page if the user not logged in
        
if(!$this->session->userdata('loggedIn')){
            
redirect('/user_authentication/');
        }
        
        
// Get user info from session
        
$data['userData'] = $this->session->userdata('userData');
        
        
// Load user profile view
        
$this->load->view('user_authentication/profile',$data);
    }
    
    public function 
logout(){
        
// Reset OAuth access token
        
$this->google->revokeToken();
        
        
// Remove token and user data from the session
        
$this->session->unset_userdata('loggedIn');
        
$this->session->unset_userdata('userData');
        
        
// Destroy entire session data
        
$this->session->sess_destroy();
        
        
// Redirect to login page
        
redirect('/user_authentication/');
    }
    
}

Models (application/models/)

User.php
The User model is used to insert/update data in the users table.

  • __construct() – Define the database table name and primary key.
  • checkUser() – Insert or update the user account data in the database based on the OAuth provider and ID.
<?php 
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
User extends CI_Model {
    
    function 
__construct() {
        
$this->tableName 'users';
    }
    
    public function 
checkUser($data = array()){
        
$this->db->select('id');
        
$this->db->from($this->tableName);
        
        
$con = array(
            
'oauth_provider' => $data['oauth_provider'],
            
'oauth_uid' => $data['oauth_uid']
        );
        
$this->db->where($con);
        
$query $this->db->get();
        
        
$check $query->num_rows();
        if(
$check 0){
            
// Get prev user data
            
$result $query->row_array();
            
            
// Update user data
            
$data['modified'] = date("Y-m-d H:i:s");
            
$update $this->db->update($this->tableName$data, array('id' => $result['id']));
            
            
// Get user ID
            
$userID $result['id'];
        }else{
            
// Insert user data
            
$data['created'] = date("Y-m-d H:i:s");
            
$data['modified'] = date("Y-m-d H:i:s");
            
$insert $this->db->insert($this->tableName$data);
            
            
// Get user ID
            
$userID $this->db->insert_id();
        }
        
        
// Return user ID
        
return $userID?$userID:false;
    }

}

Views (application/views/)

user_authentication/index.php
In this view, the Sign-In with Google account button is displayed and it redirects the user to the Google OAuth URL.

<h2>CodeIgniter Google Login</h2>
<!-- Display sign in button -->
<a href="<?php echo $loginURL?>"><img src="<?php echo base_url('assets/images/google-sign-in-btn.png'); ?>" /></a>

user_authentication/profile.php
If the user logged in with their Google account, the profile details are shown with a Logout link.

<h2>Google Account Details</h2>
<div class="ac-data">
    <!-- Display Google profile information -->
    <img src="<?php echo $userData['picture']; ?>"/>
    <p><b>Google ID:</b> <?php echo $userData['oauth_uid']; ?></p>
    <p><b>Name:</b> <?php echo $userData['first_name'].' '.$userData['last_name']; ?></p>
    <p><b>Email:</b> <?php echo $userData['email']; ?></p>
    <p><b>Gender:</b> <?php echo $userData['gender']; ?></p>
    <p><b>Locale:</b> <?php echo $userData['locale']; ?></p>
    <p><b>Logged in with:</b> Google</p>
    <p>Logout from <a href="<?php echo base_url().'user_authentication/logout'?>">Google</a></p>
</div>

Conclusion

We have tried to make the Google login integration easier for CodeIgniter application. Google API client library makes it easier to integrate login with Google in CodeIgniter. You can easily integrate Google login using our Google OAuth library for CodeIgniter. Also, you can extend the functionality of the example CodeIgniter Google authentication script as per your needs. To make the social login more user-friendly, you can add Facebook login option in CodeIgniter.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

27 Comments

  1. Nicolas Said...
  2. Shiv Om Mishra Said...
  3. Sandeep Kumar Said...
    • CodexWorld Said...
  4. Hengky Mulyono Said...
  5. Fad Muhammad Said...
  6. Deepak Mohapatra Said...
  7. Husen Said...
  8. Ketan Said...
  9. Win Said...
    • CodexWorld Said...
  10. Marijn Said...
  11. Matt Jackson Said...
    • CodexWorld Said...
  12. Brijesh Chaubey Said...
    • CodexWorld Said...
  13. Waseem Said...
  14. Duong Kien Said...
  15. Ashutosh Said...
    • CodexWorld Said...
  16. Ameya DESHPANDE Said...
  17. Cade Said...
  18. Cade Said...
    • CodexWorld Said...
  19. Cade Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up