Login with Google Account in CodeIgniter

Google OAuth API is the easiest option to integrate login system in the website. Google OAuth login system helps the user to login to the web application using their Google plus account. The main advantages of Google login are the user can login to the web application with their existing Google account without register on the website.

Google OAuth Login can be integrated into the website using PHP and JavaScript. In this tutorial, we will learn how to integrate Login with Google account in CodeIgniter using Google API PHP Client Library. The example script allows you can implement Login with Google account in CodeIgniter application and store the Google+ profile information in the MySQL database.

Before you begin to integrate Login with Google in CodeIgniter, take look at the folders and files structure.

  • codeigniter/
    • application/
      • config/
        • google.php
      • controllers/
        • User_authentication.php
      • libraries/
        • Google.php
      • models/
        • User.php
      • third_party/
        • google-api-client/
      • views/
        • user_authentication/
          • index.php
          • profile.php
    • assets/
      • images

Google Project Creation

To use Google API Client Library, you need to create a Google API project in the Google API Console. You should need to specify Authorized redirect URIs that will be the same of user authentication controller URL (http://localhost/codeigniter/user_authentication/). After project creation, the Client ID and Client secret will be generated in Google API project console.

Go through this step-by-step guide to create Google API Console Project – How to Create Google Developers Console Project

Once your Google API project creation is completed, copy the Client ID and Client secret and put them into the respective variable in the script (Google API Configuration file).

Create Database Table

To store the user profile information, you need to create a table into the database. The following SQL creates a users table in the MySQL database for inserting the Google+ profile information.

CREATE TABLE `users` (
 `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,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config (application/config/)

Some libraries and helper are needed for Google login, it’s a better idea to specify these once in the autoload.php file.

Load the session and database libraries:

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

Load the URL helper:

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

Google API configuration variables are defined in this file. You need to specify the Client ID, Client secret and Redirect URI according to your Google API Console Project credentials.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
| -------------------------------------------------------------------
|  Google API Configuration
| -------------------------------------------------------------------
|  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']     = 'http://localhost/codeigniter/user_authentication/';
$config['google']['application_name'] = 'Login to CodexWorld.com';
$config['google']['api_key']          = '';
$config['google']['scopes']           = array();

Google API PHP Client Library (application/third_party/)

Google API PHP client is used to connect with Google OAuth API, place the google-api-client library in the third_party/ directory of CodeIgniter application.

Note that: You will get the Google API client library files in our source code.

Google OAuth Library (application/libraries/)

The Google class helps to integrate Google API client in CodeIgniter 3.x application. You can easily add the Login with Google functionality using PHP API client and Google library.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
 * Google OAuth Library for CodeIgniter 3.x
 * Library for Google+ login. It helps the user to login with their Google account
 * in CodeIgniter application.
 * This library requires the Google API PHP client and it should be placed in third_party folder.
 * It also requires google configuration file and it should be placed in the config directory.
 * @package     CodeIgniter
 * @category    Libraries
 * @author      CodexWorld
 * @license     http://www.codexworld.com/license/
 * @link        http://www.codexworld.com
 * @version     2.0
class Google{
    public function 
$CI =& get_instance();
APPPATH .'third_party/google-api-client/Google_Client.php';
APPPATH .'third_party/google-api-client/contrib/Google_Oauth2Service.php';
$this->client = new Google_Client();
$this->oauth2 = new Google_Oauth2Service($this->client);
    public function 
loginURL() {
    public function 
getAuthenticate() {
    public function 
getAccessToken() {
    public function 
setAccessToken() {
    public function 
revokeToken() {
    public function 
getUserInfo() {

Login with Google Account using PHP

Controller (application/controllers/User_authentication.php)

The User_Authentication controller contains four functions, __construct(), index(), profile(), and logout().

  • __construct() – The Google library and User model are loaded in this method.
  • index() – The following functionalities are implemented in this method.
    • Connects with Google OAuth API using the Google library, authenticate, and fetch the Google plus profile information.
    • Pass the user profile information to the User model to insert into the database.
    • Loads the login view for the non-authenticated user.
  • profile() – Retrieve the user data from session and load the profile view to display the user’s profile info.
  • logout() – Removes the user data from session and log out the user from their Google account.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
User_Authentication extends CI_Controller
//load google login library
//load user model
    public function 
//redirect to profile page if user already logged in
if($this->session->userdata('loggedIn') == true){
//authenticate user
//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['profile_url']    = !empty($gpInfo['link'])?$gpInfo['link']:'';
$userData['picture_url']    = !empty($gpInfo['picture'])?$gpInfo['picture']:'';
//insert or update user data to the database
$userID $this->user->checkUser($userData);
//store status & user info in session
//redirect to profile page
//google login url
$data['loginURL'] = $this->google->loginURL();
//load google login view
    public function 
//redirect to login page if user not logged in
//get user info from session
$data['userData'] = $this->session->userdata('userData');
//load user profile view
    public function 
//delete login status & user info from session
//redirect to login page

Models (application/models/User.php)

The User model contains one function called checkUser(), it is used to insert or update the user profile information into the database.

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


Views (application/views/)

This view file displays the login button to sign with Google account. This button redirects the user to the auth URL.

<h1>CodeIgniter Sign In With Google Account</h1>
<a href="<?php echo $loginURL?>"><img src="<?php echo base_url().'assets/images/glogin.png'?>" /></a>

This view shows the Google plus profile information with a logout link.

<h1>CodeIgniter Sign In With Google Account</h1>
<div class="wrapper">
    <div class="info-box">
        <p class="image"><img src="<?php echo @$userData['picture_url']; ?>" width="300" height="220"/></p>
        <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>Google+ Link: </b><a href="<?php echo @$userData['profile_url']; ?>" target="_blank"><?php echo @$userData['profile_url']; ?></a></p>
        <p><b>Logout from <a href="<?php echo base_url().'user_authentication/logout'?>">Google</a></b></p>

Login with Google Account using JavaScript


That’s all! Now open the user authentication URL (http://localhost/codeigniter/user_authentication/) on the browser and check the login system with Google in CodeIgniter. Hope, our example script will help you to integrate Google login in your CodeIgniter application. All files including Google API PHP Client library are included into the Source Code package, download it and place the files into the CodeIgniter application as per the instructions.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You


  1. Fad Muhammad Said...
  2. Deepak Mohapatra Said...
  3. Husen Said...
  4. Ketan Said...
  5. Win Said...
    • CodexWorld Said...
  6. Marijn Said...
  7. Matt Jackson Said...
    • CodexWorld Said...
  8. Brijesh Chaubey Said...
    • CodexWorld Said...
  9. Waseem Said...
  10. Duong Kien Said...
  11. Ashutosh Said...
    • CodexWorld Said...
  12. Ameya DESHPANDE Said...
  13. Cade Said...
  14. Cade Said...
    • CodexWorld Said...
  15. Cade Said...
    • CodexWorld Said...

Leave a reply