Google LogIn in CodeIgniter

Google LogIn in CodeIgniter

In this blog we will learn how to use Google login on website, many websites uses google login, google login is best for user experience, sometimes users don’t want to create a profile on the website then he can log in via google.

Let’s see the following steps to use google login :

  1. Create Goolge API Credentials
  2. Download Google API library
  3. Set Base URL of the project and autoload files
  4. Database Connection Settings
  5. Create Controller for Google Login
  6. Create Models for Google login
  7. Create View for Google Login

Create Google API Credentials

To use Google Login, the first step is to create Google API, Let’s see the following steps:

Step1:  Go to the following URL:

Step2:  Once you have opened the above link click on create a project

After clicking on the new project following screen appear, enter your project name and click on create button.

Click on the OAuth consent screen link, you will see the following screen; select external and click on create button.

 Once you click on create button, you will redirect to a new page, on this page you have to enter the following details:

App Name
User support email
App domain
Email addresses

After fill-up, the following detail clicks on the save and continue button.

After completing page creation, click on credentials, on the credentials page click on create credentials following dropdown will be shown, select the OAuth client ID.

Ater selecting OAuth client ID following screen appears, on this select web application from the dropdown.

After the selection of the web application from the dropdown following fields will appear, you have to enter your application name and in authorized redirect URI; you have to enter your domain URL and click on create button.

After completing the step8 following screen appear; copy your client id and client secret and paste it into your google_login controller file.  

Download Google API library

After creating Google API Credentials, now we have to download the Google API library by using composer, run the following command in your cmd change directory as per your requirement.

composer require google/apiclient:"^2.0"

Set Base url of project and autoload files:

Set base url in application>config.php file

$config['base_url'] = 'http://localhost/googlelogin/';

Autoload files:

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

Database Connection Settings:

Set database connection setting in your database.php file

$db['default'] = array(
                'dsn'       => '',
                'hostname' => 'localhost',
                'username' => 'root',
                'password' => '',
                'database' => 'googlelogin',
                'dbdriver' => 'mysqli',
                'dbprefix' => '',
                'pconnect' => FALSE,
                'db_debug' => (ENVIRONMENT !== 'production'),
                'cache_on' => FALSE,
                'cachedir' => '',
                'char_set' => 'utf8',
                'dbcollat' => 'utf8_general_ci',
                'swap_pre' => '',
                'encrypt' => FALSE,
                'compress' => FALSE,
                'stricton' => FALSE,
                'failover' => array(),
                'save_queries' => TRUE

Create Controller Google_login.php:

Create Controller Google_login.php and paste the following code:

defined('BASEPATH') OR exit('No direct script access allowed');
class Google_login extends CI_Controller {
 public function __construct()
 function login()
  include_once APPPATH . "libraries/vendor/autoload.php";
  $google_client = new Google_Client();
  $google_client->setClientId('’); //Define your ClientID
  $google_client->setClientSecret(‘'); //Define your Client Secret Key
  $google_client->setRedirectUri(''); //Define your Redirect Uri
   $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
    $this->session->set_userdata('access_token', $token['access_token']);
    $google_service = new Google_Service_Oauth2($google_client);
    $data = $google_service->userinfo->get();
    $current_datetime = date('Y-m-d H:i:s');
     //update data
     $user_data = array(
      'first_name' => $data['given_name'],
      'last_name'  => $data['family_name'],
      'email_address' => $data['email'],
      'profile_picture'=> $data['picture'],
      'updated_at' => $current_datetime
     $this->google_login_model->Update_user_data($user_data, $data['id']);
     //insert data
     $user_data = array(
      'login_oauth_uid' => $data['id'],
      'first_name'  => $data['given_name'],
      'last_name'   => $data['family_name'],
      'email_address'  => $data['email'],
      'profile_picture' => $data['picture'],
      'created_at'  => $current_datetime
    $this->session->set_userdata('user_data', $user_data);
  $login_button = '';
   $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="'.base_url().'asset/sign-in-with-google.png" /></a>';
   $data['login_button'] = $login_button;
   $this->load->view('google_login', $data);
   $this->load->view('google_login', $data);
 function logout()

Create Model file Google_login_model.php

Create model file Google_login_model.php  in models folder  and paste the following code:

class Google_login_model extends CI_Model
 function Is_already_register($id)
  $this->db->where('login_oauth_uid', $id);
  $query = $this->db->get('chat_user');
  if($query->num_rows() > 0)
   return true;
   return false;
 function Update_user_data($data, $id)
  $this->db->where('login_oauth_uid', $id);
  $this->db->update('chat_user', $data);
 function Insert_user_data($data)
  $this->db->insert('chat_user', $data);

Create a view file google_login.php

Create a file google_login.php in views folder and paste the following code:

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Login with Google in Codeigniter</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src=""></script>
  <script src=""></script>
  <link href="" rel="stylesheet" />
  <div class="container">
   <br />
   <h2 align="center">Login using Google Account with Codeigniter</h2>
   <br />
   <div class="panel panel-default">
    $user_data = $this->session->userdata('user_data');
    echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
    echo '<img src="'.$user_data['profile_picture'].'" class="img-responsive img-circle img-thumbnail" />';
    echo '<h3><b>Name : </b>'.$user_data["first_name"].' '.$user_data['last_name']. '</h3>';
    echo '<h3><b>Email :</b> '.$user_data['email_address'].'</h3>';
    echo '<h3><a href="'.base_url().'google_login/logout">Logout</h3></div>';
    echo '<div align="center">'.$login_button . '</div>';

Download Source Code