Why Use Google Login in Your CodeIgniter 4 Application?

             

Integrating Google OAuth login (also called "Sign in with Google") offers several key advantages over traditional email/password registration:

  • Improved User Experience: One-click login reduces friction and abandonment rates during signup.
  • Enhanced Security: Google handles password management, 2FA, and account recovery — reducing your app's attack surface.
  • Higher Conversion Rates: Studies show social logins can increase sign-ups by 20–40%.
  • Rich User Data: Instantly access verified name, email, and profile picture (with user consent).

In CodeIgniter 4, this integration is straightforward using the official Google API Client library — no need for complex third-party auth packages.



Implement Google Login (OAuth 2.0) in CodeIgniter 4 – Complete Tutorial with Example Code

Table Of Content

1 Prerequisites

  • PHP ≥8.1 (recommended 8.2+)
  • Composer
  • CodeIgniter 4 installed
  • Google Account + access to Google Cloud Console

2 What is Google OAuth 2.0 and How Does It Work with CodeIgniter 4?

Google OAuth 2.0 is an open standard authorization framework that allows your application to securely access limited user data from Google accounts without needing passwords.

The flow in a CodeIgniter 4 app looks like this:

  1. User clicks "Sign in with Google" → redirects to Google's consent screen.
  2. User grants permission → Google redirects back to your callback URL with an authorization code.
  3. Your server exchanges the code for access/refresh tokens.
  4. Use the tokens to fetch user profile info (email, name, ID, picture).
  5. Store session data and log the user in.

This tutorial uses the google/apiclient Composer package to handle the heavy lifting.

Follow these steps to add secure Google authentication to your CodeIgniter 4 project in under 30 minutes.

3 Install Codeigniter 4 Project

First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.

composer create-project codeigniter4/appstarter ci4-google-login

Then, navigate to your project directory:

cd ci4-google-login

4 Install Google API Client Library

First, make sure your computer has a composer.
Use the following command to install Google Client Library via Composer.

composer require google/apiclient:^2.0

This command will download the google apiclient Library and add it to your project.

5 Set Up Google OAuth Credentials


5.1 Login into Google Developer Account

If you have Google Developer Account Go to https://console.cloud.google.com/, else you can easily create one directly from the Google Developers Console.

5.2 Create New Project

Create a Project in the Google Developer Console

Create Project

Entering Project information in the following Screen

Project Details

Project successfully created with given information's

Project Created Successfully

5.3 Create Credentials

Now Create the credential by choosing "Credentials" in the side bar, click "Create Credentials" button and choose "OAuth Client ID".

Create Credentials

Now Click "Configure Consent Screen" Button.

Configure Consent Screen

It will redirected to the following screen and choose "External" option then create.

external

5.5 Update App Information

By providing App and Developer Information Complete the form then click "Save and Continue" Button.

App Information

5.6 OAuth Client Created

Now Create the OAuth Client by choosing "Credentials" in the side bar, click "Create Credentials" button and choose "OAuth Client ID".

Create Credentials

It will redirected to the following screen and fill the detail about our app and fill the authorized redirect URIs. This is the URI that we will use to redirect user after they choose their Google account to login to our web. For example here I use http://127.0.0.1:8000/callback/google for the callback URI..

Create Oauth

Now we get the Client ID and the Client Secret.

Oauth Successfully

6 Configure Credentials in CodeIgniter

Insert the Client ID and Client Secret key and redirect URI into the .env file, Which we obtained from previous step GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. Additionally, include a new key in the .env file called GOOGLE_REDIRECT_URI and populate it with the callback URI used in the Google API Console.

GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REDIRECT_URI=http://localhost:8080/auth/google_callback

7 Create New Controller - AuthController

In this controller, implement methods like login, googleLogin, googleCallback, dashboard, and logout. The googleLogin method will generate the Google login URL, and googleCallback will handle the OAuth response. Here is a sample code for Google login in Codeigniter 4:
Use the following artisan command to Create Controller.

php spark make:controller AuthController

app/Controllers/AuthController.php

<?php
namespace App\Controllers;

use CodeIgniter\Controller;
use Google\Client;
use Google\Service\Oauth2;

class AuthController extends Controller
{
    protected $googleClient;

    public function __construct()
    {
        // Initialize Google Client
        $this->googleClient = new Client();
        $this->googleClient->setClientId(env('GOOGLE_CLIENT_ID'));
        $this->googleClient->setClientSecret(env('GOOGLE_CLIENT_SECRET'));
        $this->googleClient->setRedirectUri(env('GOOGLE_REDIRECT_URI'));
        $this->googleClient->addScope('email');
        $this->googleClient->addScope('profile');
        $this->googleClient->setAccessType('offline'); // Optional: for refresh tokens
    }

    // Display login page
    public function login()
    {
        return view('auth/login');
    }

    // Redirect to Google for authentication
    public function googleLogin()
    {
        $authUrl = $this->googleClient->createAuthUrl();
        return redirect()->to($authUrl);
    }

    // Handle Google callback
    public function googleCallback()
    {
        $code = $this->request->getVar('code');

        if (!$code) {
            return redirect()->to('/login')->with('error', 'Authorization code missing.');
        }

        try {
            $token = $this->googleClient->fetchAccessTokenWithAuthCode($code);

            if (isset($token['error'])) {
                throw new \Exception($token['error_description'] ?? 'Unknown error');
            }

            $this->googleClient->setAccessToken($token);

            // Get user info
            $oauthService = new Oauth2($this->googleClient);
            $userInfo = $oauthService->userinfo->get();

            // Store user data in session
            $userData = [
                'google_id'    => $userInfo->id,
                'name'         => $userInfo->name,
                'email'        => $userInfo->email,
                'picture'      => $userInfo->picture,
                'is_logged_in' => true
            ];

            session()->set($userData);

            return redirect()->to('/dashboard');
        } catch (\Exception $e) {
            return redirect()->to('/login')->with('error', 'Login failed: ' . $e->getMessage());
        }
    }

    // Display dashboard (protected)
    public function dashboard()
    {
        if (!session()->get('is_logged_in')) {
            return redirect()->to('/login')->with('error', 'Please log in first.');
        }

        $data['user'] = session()->get();
        return view('auth/dashboard', $data);
    }

    // Logout
    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login')->with('success', 'Logged out successfully.');
    }
}

?>

8 Create Index View File

Create folder app/Views/auth/ Create View "index.php" File to Show Form app/Views/auth/login.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        .btn-google { background-color: #4285F4; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
    <h1>Login to Your Account</h1>
    
    <?php if (session()->getFlashdata('error')): ?>
        <p class="error"><?= session()->getFlashdata('error') ?></p>
    <?php endif; ?>
    
    <?php if (session()->getFlashdata('success')): ?>
        <p class="success"><?= session()->getFlashdata('success') ?></p>
    <?php endif; ?>
    
    <a href="<?= site_url('auth/google') ?>" class="btn-google">Login with Google</a>
</body>
</html>

9 Create Dashboard View File

Create View "dashboard.php" File to Show Form app/Views/auth/dashboard.php:

<!DOCTYPE html>
&<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        img { border-radius: 50%; width: 100px; height: 100px; }
        .logout { background-color: #f44336; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>Welcome, <?= esc($user['name']) ?>!</h1>
    <img src="<?= esc($user['picture']) ?>" alt="Profile Picture">
    <p>Email: <?= esc($user['email']) ?></p>
    <a href="<?= site_url('logout') ?>" class="logout">Logout</a>
</body>
</html>

10 Define a Route

Define routes for the UploadController in the Routes.php file
app/Config/Routes.php


use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes
 */
$routes->get('/', 'Home::index');
$routes->get('/login', 'AuthController::login');
$routes->get('auth/google', 'AuthController::googleLogin');
$routes->get('auth/google_callback', 'AuthController::googleCallback');
$routes->get('/dashboard', 'AuthController::dashboard');
$routes->get('/logout', 'AuthController::logout');

11 Folder Structure

12 Run the Application

Finally, run the web server using:

php spark serve

  • Visit http://localhost:8080/login
  • Click "Login with Google"
  • Authenticate with Google
  • You'll be redirected to the dashboard showing your name, email, and profile picture
  • Logout returns to login page

Troubleshooting

  • Redirect URI Mismatch: Ensure exact match in Google Console and .env.
  • cURL Error 60 (SSL): On Windows, download cacert.pem and set in php.ini: curl.cainfo = "path/to/cacert.pem".
  • No Code in Callback: Check routes and firewall.
  • Scopes Issues: Google may prompt for consent; ensure scopes are added.
  • Production Tips: Use HTTPS (Google requires it), store sessions securely (e.g., in DB via CI config), and revoke tokens on logout if using access tokens further.

12 Conclusion

You've now added secure Google login to your CodeIgniter 4 app. Extend it with user registration (check if email exists → login or create account), database storage, etc.
Revathi M - PHP and CodeIgniter Developer

Written by Revathi M

PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel

Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.

Frequently Asked Questions

You need PHP 8.2 or higher, Composer, and a configured Google Developer Console project with OAuth Client ID.

Run the command: composer require google/apiclient:^2.0. This installs the official Google API Client Library.

Add GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and GOOGLE_REDIRECT_URI to your .env file.

In the controller constructor, create a Google_Client instance, set Client ID, Secret, Redirect URI from env, and add scopes for 'email' and 'profile'.

Use $this->googleClient->createAuthUrl() and redirect to it in the login method.

In the callback method, fetch the access token with fetchAccessTokenWithAuthCode($code), set it, use Google_Service_Oauth2 to get user info via userinfo->get(), store data in session, and redirect to dashboard.

The tutorial fetches id, name, and email from the Google userinfo endpoint.

No, user data (id, name, email) is stored only in CodeIgniter sessions. No database is required.

The GOOGLE_REDIRECT_URI in .env must exactly match the authorized redirect URI configured in Google Console OAuth credentials (e.g., http://127.0.0.1:8000/callback/google).

Create a logout method that destroys the session with session()->destroy() and redirects to the login page.