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.

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
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
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
5.2 Create a Facebook App

5.3 Configure OAuth Settings


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

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

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.


5.4 Update App Information


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

6 Configure Credentials in .env
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
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
<!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
<!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
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
12 Run Web Server to Test the App
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
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.
