Login with Google Account in CodeIgniter


After publishing Login with Google account using PHP tutorial, we’ve received the huge request for Google login integration in CodeIgniter. In this tutorial, we’ll show how can you integrate Login with Google account in CodeIgniter.

login-with-google-account-in-codeIgniter-by-codexworld

Google API PHP Client Library helps to implement Google login in CodeIgniter application. Before starting Google authentication in CodeIgniter tutorial, take a look on files structure of CodeIgniter application for Google authentication.

login-with-google-account-in-codeIgniter-folders-files-structure-by-codexworld

Google OAuth API required Client ID and Client secret which could be found from the API Credentials of Google project. You can create the project at Google Developers Console and get the API Credentials. Follow the below steps to register your application at Google Developers Console.

Google Project Creation

 Go to the Google Developers Console – https://console.developers.google.com/
 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 world-wide.
  • Click on the Create button and the project to be created within 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 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.

 Now you can see the Client ID for web application section. Note the Client ID and Client secret that will need to use to access the APIs.

google-project-creation-client-id-for-web-application-by-codexworld

Note that: Authorized redirect URI and method URL of your application controller should be same.

Once your project creation is completed, copy the API Credentials and put them into the respective variable in your script.

Database Table Creation

To store the user information, you need to create a table into the database. The users table SQL would like the below.

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(255) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(255) 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_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `profile_url` 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;

Controllers (User_authentication.php)

User_Authentication controller contains three functions __construct(), index(), and logout().

 __construct() Load the User model for insert or update the users data into the database.
 index() Google account authentication, pass the users data to User model, load the login and account view, and pass the users data to the view – all of those functionalities are implemented into this function.
 logout() This function uses to logout the users from their Google account.

You only need to change the $clientId, $clientSecret, and $redirectUrl variable value according to your API Credentials.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
User_Authentication extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
// Load user model
        
$this->load->model('user');
    }
    
    public function 
index(){
        
// Include the google api php libraries
        
include_once APPPATH."libraries/google-api-php-client/Google_Client.php";
        include_once 
APPPATH."libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
        
        
// Google Project API Credentials
        
$clientId 'Insert Google Client ID';
        
$clientSecret 'Insert Google Client secret';
        
$redirectUrl base_url() . 'user_authentication/';
        
        
// Google Client Configuration
        
$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);

        if (isset(
$_REQUEST['code'])) {
            
$gClient->authenticate();
            
$this->session->set_userdata('token'$gClient->getAccessToken());
            
redirect($redirectUrl);
        }

        
$token $this->session->userdata('token');
        if (!empty(
$token)) {
            
$gClient->setAccessToken($token);
        }

        if (
$gClient->getAccessToken()) {
            
$userProfile $google_oauthV2->userinfo->get();
            
// Preparing data for database insertion
            
$userData['oauth_provider'] = 'google';
            
$userData['oauth_uid'] = $userProfile['id'];
            
$userData['first_name'] = $userProfile['given_name'];
            
$userData['last_name'] = $userProfile['family_name'];
            
$userData['email'] = $userProfile['email'];
            
$userData['gender'] = $userProfile['gender'];
            
$userData['locale'] = $userProfile['locale'];
            
$userData['profile_url'] = $userProfile['link'];
            
$userData['picture_url'] = $userProfile['picture'];
            
// Insert or update user data
            
$userID $this->user->checkUser($userData);
            if(!empty(
$userID)){
                
$data['userData'] = $userData;
                
$this->session->set_userdata('userData',$userData);
            } else {
               
$data['userData'] = array();
            }
        } else {
            
$data['authUrl'] = $gClient->createAuthUrl();
        }
        
$this->load->view('user_authentication/index',$data);
    }
    
    public function 
logout() {
        
$this->session->unset_userdata('token');
        
$this->session->unset_userdata('userData');
        
$this->session->sess_destroy();
        
redirect('/user_authentication');
    }
}

Models (User.php)

User model contains one function named checkUser(). Using this function, we’ll insert or update the user data into the users database table.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model{
    function 
__construct() {
        
$this->tableName 'users';
        
$this->primaryKey 'id';
    }
    public function 
checkUser($data = array()){
        
$this->db->select($this->primaryKey);
        
$this->db->from($this->tableName);
        
$this->db->where(array('oauth_provider'=>$data['oauth_provider'],'oauth_uid'=>$data['oauth_uid']));
        
$prevQuery $this->db->get();
        
$prevCheck $prevQuery->num_rows();
        
        if(
$prevCheck 0){
            
$prevResult $prevQuery->row_array();
            
$data['modified'] = date("Y-m-d H:i:s");
            
$update $this->db->update($this->tableName,$data,array('id'=>$prevResult['id']));
            
$userID $prevResult['id'];
        }else{
            
$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);
            
$userID $this->db->insert_id();
        }

        return 
$userID?$userID:FALSE;
    }
}

Views (user_authentication/index.php)

This view would be loaded at the time of displaying the login button (before login) and users account details (after login).

<?php
if(!empty($authUrl)) {
    echo 
'<a href="'.$authUrl.'"><img src="'.base_url().'assets/images/glogin.png" alt=""/></a>';
}else{

?>
<div class="wrapper">     <h1>Google Profile Details </h1>
    <?php
    
echo '<div class="welcome_txt">Welcome <b>'.$userData['first_name'].'</b></div>';
    echo 
'<div class="google_box">';
    echo 
'<p class="image"><img src="'.$userData['picture_url'].'" alt="" width="300" height="220"/></p>';
    echo 
'<p><b>Google ID : </b>' $userData['oauth_uid'].'</p>';
    echo 
'<p><b>Name : </b>' $userData['first_name'].' '.$userData['last_name'].'</p>';
    echo 
'<p><b>Email : </b>' $userData['email'].'</p>';
    echo 
'<p><b>Gender : </b>' $userData['gender'].'</p>';
    echo 
'<p><b>Locale : </b>' $userData['locale'].'</p>';
    echo 
'<p><b>Google+ Link : </b>' $userData['profile_url'].'</p>';
    echo 
'<p><b>You are login with : </b>Google</p>';
    echo 
'<p><b>Logout from <a href="'.base_url().'user_authentication/logout">Google</a></b></p>';
    echo 
'</div>';
    
?>
</div>
<?php ?>

Libraries (google-api-php-client/)

Insert the Google API PHP Client folder in the libraries/ folder. You can find the complete folder into our downloadable package.

Config (autoload.php)

Open the application/config/autoload.php file and load the following libraries and helper.

Load the session and database libraries.

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

Load the URL helper.

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

Conclusion

That’s all! Now open the application URL (http://localhost/codeigniter/user_authentication) on the browser and check the login system with Google account in CodeIgniter. Also, you can read our previous article for integrating Login with Google account using PHP. If you have any query or suggestion, don’t hesitate to comment here.

12 Comments

  1. Brijesh Chaubey Said...
    • CodexWorld Said...
  2. Waseem Said...
  3. Duong Kien Said...
  4. Ashutosh Said...
    • CodexWorld Said...
  5. Ameya DESHPANDE Said...
  6. Cade Said...
  7. Cade Said...
    • CodexWorld Said...
  8. Cade Said...
    • CodexWorld Said...

Leave a reply

Connect With CodexWorld