CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New
Need a Website Or Web Application Contact : +91 9437911966 (Whatsapp) Note: Paid Service

How to Login with Google Account in CodeIgniter


Sql Table

 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;

autoload.php

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

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

google.php

<?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();

user_authentication.php

<?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/'); 
    } 
     
}

user.php

<?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; 
    } 
 
}

user_authentication/index.php

    <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

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