How to use google to sign in into php codeigniter 3 ?

use google to sign in into php codeigniter 3

Use Google to sign in into php codeigniter 3.

If You want to use google to sign in into php codeigniter 3 using google account then this artical for you.
Google provides google oauth api for use google account for login as google into php codeigniter 3.
It Provides google oauth 2.0 api whis is very powerfull and useful for login api authentication for login as google.
Using this google oauth api ,We can access User data From Server, and api authentication user data via Google account for login as google.

In This Post We Will Learn How to implement google account to Codeigniter webiste for login,
Follow Bellow step by step codeigniter for login as google in php codeigniter 3.

Create Google API Credential

  1. If you are logged in  into Google or gmail account, then you have go to  https://console.developers.google.com/ url.
  2. Once you opened the google developers  link, then first you have to create new project by click on create project link.
  3. In ne Project  we have enter project name and click on create button
  4. After that we have to click on OAuth consent screen link
  5. Select external user type
  6. Set Application Name and save the project
  7. Then Click on credentials button 
  8. Create New Credentials
  9. Select google oauth 2.0 client id and Select application type as Web Application
  10. Set Redirect Url 
  11. Download google sign in client id and Secret id .

Download Google API oauth client library

There Are Two types to get or download google api library for login as google in php codeigniter 3

  1. Using Composer 
  2. composer require google/apiclient:"^2.0"

Set Autoload Library

Autoload library is use to load libraries one time which we can use this libraries in multiple tiomes

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

Set Base Url For Phph Codeigniter 3 application

syntax : base_url();

$config['base_url'] = 'http://localhost/google-login/';

Connect Database for php codeigniter 3 application.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'codeigniter_chat',
 '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 For login  as google.

<?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 for Login as google in php codeigniter 3.

Path : google-login / application / model / Google_login_model.php

<?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 view for Login as Google in php codeigniter 3.

Path : google-login / application / view / login.php

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

Thank You ….

I Hope , It Will Help you to integrate Google login system in codeigniter application . 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top