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:  https://console.developers.google.com/

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


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


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


Step5:
 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.


Step6:  
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.


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


Step8:
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.


Step9:
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:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Google_login extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('google_login_model');
 }
 
 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
 
  $google_client->addScope('email');
 
  $google_client->addScope('profile');
 
  if(isset($_GET["code"]))
  {
   $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
 
   if(!isset($token["error"]))
   {
    $google_client->setAccessToken($token['access_token']);
 
    $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');
 
    if($this->google_login_model->Is_already_register($data['id']))
    {
     //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']);
    }
    else
    {
     //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->google_login_model->Insert_user_data($user_data);
    }
    $this->session->set_userdata('user_data', $user_data);
   }
  }
  $login_button = '';
  if(!$this->session->userdata('access_token'))
  {
   $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);
  }
  else
  {
   $this->load->view('google_login', $data);
  }
 }
 
 function logout()
 {
  $this->session->unset_userdata('access_token');
 
  $this->session->unset_userdata('user_data');
 
  redirect('google_login/login');
 }
 
}
?>
 


Create Model file Google_login_model.php

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

<?php
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;
  }
  else
  {
   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:

<html>
 <head>
  <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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
 
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">Login using Google Account with Codeigniter</h2>
   <br />
   <div class="panel panel-default">
   <?php
   if(!isset($login_button))
   {
 
    $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>';
   }
   else
   {
    echo '<div align="center">'.$login_button . '</div>';
   }
   ?>
   </div>
  </div>
 </body>
</html>

Download Source Code

Categories: web development codeigniter

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Request For Demo