What is the Facebook Graph SDK and Why Use It in CodeIgniter 4?

             

The Facebook Graph SDK is the official (or best-maintained) PHP library that makes it easy to use Meta’s Graph API — especially for Facebook Login (OAuth 2.0).

It helps you:

  • Generate the Facebook login button / URL
  • Handle the callback and get the access token
  • Fetch user data (ID, name, email, picture…)
  • Make secure API calls with very little code

Why use it in CodeIgniter 4?

  • Saves time — no need to write complex OAuth logic yourself
  • Safer — handles token exchange, redirects and errors correctly
  • Clean code — simple methods like $fb->get('/me?fields=id,name,email')
  • Up-to-date — maintained forks support PHP 8.1+ and recent Graph API versions
  • CI4 friendly — installs easily via Composer and works perfectly with .env

Bottom line: Facebook Graph SDK is the fastest and most reliable way to add Facebook login to CodeIgniter 4.



Facebook Login in CodeIgniter 4: Complete Step-by-Step Tutorial (Using Graph SDK & OAuth 2.0)

Table Of Content

1 Prerequisites

  • PHP 8.1+ (recommended 8.2 or higher)
  • Composer installed
  • Basic knowledge of CodeIgniter 4
  • A Facebook Developer account

2 Introduction

In today's web applications, social login options like Facebook login improve user experience by eliminating the need for separate registrations. This CodeIgniter 4 Facebook login tutorial shows you how to integrate Facebook OAuth 2.0 authentication using the official Facebook Graph SDK via Composer. Users can log in securely, and you'll retrieve basic profile data (ID, name, email) to store in session or database.

By the end, you'll have a working Facebook login system in CodeIgniter 4 ready for production use.

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

Then, navigate to your project directory:

cd ci4-facebook-login

4 Install Facebook Graph SDK

First, make sure your computer has a composer.
Use the following command to install Facebook SDK via Composer.

composer require facebook/graph-sdk

This command will download the Facebook sdk and add it to your project.

5 Create a Facebook App and Get OAuth Credentials

5.1 Login into Facebook Developers Portal

If you have Facebook Developer Account Go to https://developers.facebook.com/, else you can easily create one directly from the Facebook Developers Portal.

5.2 Create a Facebook App

Click on "Create App" Button and follow the prompts to create a new Facebook App
Facebook Create App
Create an App in the Facebook/Meta Admin


5.3 Configure OAuth Settings

In Following Screen select "Authenticate and request data from users with Facebook Login" Option Facebook Add Use Case
Facebook Login Type

Fill the Details of the App in following Screen and Press " Create App " Button Facebook App Details

In the Facebook App dashboard, navigate to " App Settings" Menu and then "Basic" Facebook App Settings

Now Copy App Id and App Secret to update in .env file and enter the website Domain URL in App Domains field, Again Scroll down in same screen to "Add Platform" details then Select Website and update Site URL. Facebook App Add Platform

Facebook App Site URL

5.4 Update App Information

Now go to "Use Cases" tab then click "Customize" Button and select "settings" option Facebook Use Cases Customize

Facebook App Use Case Setting

Now fill the authorised redirect URIs. This is the URI that we will use to redirect user after they choose their Facebook account to login to our web. For example here I use http://127.0.0.1:8000/callback/facebook for the callback URI..
Facebook App Setting

Client OAuth Settings Add OAuth Redirect URI in the Facebook/Meta Admin.

6 Configure Credentials in .env

Insert the Facebook App ID and Facebook App Secret key and redirect URI into the .env file, Which we obtained from previous step FACEBOOK_APP_ID and FACEBOOK_APP_SECRET. Additionally, include a new key in the .env file called FACEBOOK_REDIRECT_URI and populate it with the callback URI used in the Facebook/Meta Admin.

FACEBOOK_APP_ID = 'your-app-id'
FACEBOOK_APP_SECRET = 'your-app-secret'
FACEBOOK_REDIRECT_URI = 'http://localhost:8080/auth/facebook/callback'
FACEBOOK_GRAPH_VERSION = 'v20.0'  # Use latest stable version

7 Create FacebookAuthController

Generate the controller:

php spark make:controller FacebookAuthController

app/Controllers/FaceookAuthController.php In the controller, implement the methods for login, callback, dashboard, and logout using the Login Facebook via Oauth 2.0 mechanism.

<?php
namespace App\Controllers;

use CodeIgniter\Controller;
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;

class FacebookAuthController extends Controller
{
    protected $facebook;

    public function __construct()
    {
        $this->facebook = new Facebook([
            'app_id' => env('FACEBOOK_APP_ID'),
            'app_secret' => env('FACEBOOK_APP_SECRET'),
            'default_graph_version' => env('FACEBOOK_GRAPH_VERSION', 'v20.0'),
        ]);
    }

    public function login()
    {
        return view('facebook_login');
    }

    public function facebookLogin()
    {
        $helper = $this->facebook->getRedirectLoginHelper();
        $permissions = ['email']; // Add more if needed, e.g., 'public_profile'
        $loginUrl = $helper->getLoginUrl(env('FACEBOOK_REDIRECT_URI'), $permissions);
        return redirect()->to($loginUrl);
    }

    public function callback()
    {
        $helper = $this->facebook->getRedirectLoginHelper();

        try {
            $accessToken = $helper->getAccessToken();
        } catch (FacebookResponseException $e) {
            // When Graph returns an error
            session()->setFlashdata('error', 'Graph error: ' . $e->getMessage());
            return redirect()->to('/auth/facebook');
        } catch (FacebookSDKException $e) {
            // When validation fails or other local issues
            session()->setFlashdata('error', 'Facebook SDK error: ' . $e->getMessage());
            return redirect()->to('/auth/facebook');
        }

        if (!isset($accessToken)) {
            if ($helper->getError()) {
                session()->setFlashdata('error', "Error: {$helper->getError()}\nReason: {$helper->getErrorReason()}\nDescription: {$helper->getErrorDescription()}");
            } else {
                session()->setFlashdata('error', 'Bad request');
            }
            return redirect()->to('/auth/facebook');
        }

        // Get long-lived access token (optional, for better UX)
        $oAuth2Client = $this->facebook->getOAuth2Client();
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);

        try {
            // Get user data
            $response = $this->facebook->get('/me?fields=id,name,email', $longLivedAccessToken);
            $user = $response->getGraphUser();
        } catch (FacebookResponseException $e) {
            session()->setFlashdata('error', 'Graph error fetching user: ' . $e->getMessage());
            return redirect()->to('/auth/facebook');
        } catch (FacebookSDKException $e) {
            session()->setFlashdata('error', 'SDK error fetching user: ' . $e->getMessage());
            return redirect()->to('/auth/facebook');
        }

        // Store user data in session (you can extend to database)
        session()->set([
            'fb_id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email'] ?? 'No email provided',
            'logged_in' => true,
        ]);

        return redirect()->to('/dashboard');
    }

    public function dashboard()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/auth/facebook');
        }
        $data = [
            'name' => session()->get('name'),
            'email' => session()->get('email'),
            'fb_id' => session()->get('fb_id'),
        ];
        return view('dashboard', $data);
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/auth/facebook');
    }
}
?>

8 Create Index View File

Design the view in app/Views/facebook_login.php to include the login button and initiate the Login with Facebook in CodeIgniter process.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Facebook Login - CodeIgniter 4</title>
</head>
<body>
    <h2>Login with Facebook in CodeIgniter 4</h2>
    <?php if (session()->getFlashdata('error')): ?>
        <p style="color: red;"><?= esc(session()->getFlashdata('error')) ?></p>
    <?php endif; ?>
    <a href="<?= base_url('auth/facebook/login') ?>">Login with Facebook</a>
</body>
</html>

9 Create Dashboard View File

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard - CodeIgniter 4</title>
</head>
<body>
    <h2>Welcome, <?= esc($name) ?>!</h2>
    <p>Email: <?= esc($email) ?></p>
    <p>Facebook ID: <?= esc($fb_id) ?></p>
    <a href="<?= base_url('auth/facebook/logout') ?>">Logout</a>
</body>
</html>

10 Define a Route

Edit app/Config/Routes.php and add these routes (inside the $routes->group() or at the end):


use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes
 */
$routes->group('auth/facebook', function ($routes) {
    $routes->get('/', 'FacebookAuthController::login');
    $routes->get('login', 'FacebookAuthController::facebookLogin');
    $routes->get('callback', 'FacebookAuthController::callback');
    $routes->get('logout', 'FacebookAuthController::logout');
});

$routes->get('dashboard', 'FacebookAuthController::dashboard');


11 Folder Structure

Ensure the folder structure is correctly set up with controllers, views, and routes to maintain the app's organization.

12 Run Web Server to Test the App

Finally, run your development server to test Login with Facebook Account in CodeIgniter 4 functionality:

php spark serve

  • Visit http://localhost:8080/auth/facebook.
  • Click "Login with Facebook" – it should redirect to Facebook, ask for permissions, then back to your app's dashboard with user data.

Troubleshooting:

  • "Invalid Redirect URI": Ensure URIs match exactly in Facebook settings and .env.
  • No email: Some users hide email; request 'email' permission explicitly.
  • SDK Errors: Update Composer packages (composer update).

Extensions: Add database integration by creating a Users model and saving data in callback().

13 Conclusion

You now have a fully functional Facebook login in CodeIgniter 4! This uses modern OAuth 2.0 practices and can be extended for Google login, user registration, 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 Facebook Developer App with App ID, App Secret, and valid redirect URI.

Run the command: composer require facebook/graph-sdk. This installs the official Facebook Graph SDK.

Add FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, and FACEBOOK_REDIRECT_URI to your .env file.

In the controller's __construct(), create a new Facebook instance with app_id, app_secret, and default_graph_version 'v12.0' from env variables.

Use $helper = $fb->getRedirectLoginHelper(); then $loginUrl = $helper->getLoginUrl(env('FACEBOOK_REDIRECT_URI'), ['email']); and redirect or link to it.

In facebookCallback(), get the access token via helper, exchange for long-lived token, fetch user data (/me?fields=id,name,email), store in session, and redirect to dashboard.

The tutorial fetches id, name, and email using the Graph API endpoint '/me?fields=id,name,email'.

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

The FACEBOOK_REDIRECT_URI in .env must exactly match the authorized redirect URI configured in your Facebook App settings.

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