Login with Facebook Account in CodeIgniter 4 - Step-by-Step Guide
Implementing Facebook account authentication is very popular these days. It is an easy and powerful method for user authentication, allowing users to log in with their Facebook accounts. This method reduces the effort required for registration or login, as users don't need to remember separate usernames and passwords.
Table Of Content
1 Prerequisites
1.) PHP version of 8.2
2.) Composer
3.) Facebook SDK
2 Introduction
In this article, we will explore how to implement Login with Facebook in CodeIgniter using the Facebook SDK. We'll be integrating Login Facebook via Oauth 2.0 in a CodeIgniter 4 application to authenticate users through their Facebook accounts.
3 Install Codeigniter 4 Project
First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.
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 Facebook App 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
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
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 go to "Use Cases" tab then click "Customize" Button and select "settings" option
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..
Client OAuth Settings Add OAuth Redirect URI in the Facebook/Meta Admin.
6 Configure Facebook App Credentials
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 Client ID
FACEBOOK_APP_SECRET=Your Client Secret
FACEBOOK_REDIRECT_URI=http://127.0.0.1:8000/auth/facebook_callback
7 Create New Controller - FaceookAuthController
Create a new controller to handle Facebook login functionality. Use the following artisan command:
php spark make:controller FaceookAuthController
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;
class FaceookAuthController extends Controller
{
private $facebook;
public function __construct()
{
$this->facebook = new Facebook([
'app_id' => getenv('FACEBOOK_APP_ID'),
'app_secret' => getenv('FACEBOOK_APP_SECRET'),
'default_graph_version' => 'v12.0',
]);
}
public function Login()
{
return view('index');
}
public function facebookLogin()
{
$helper = $this->facebook->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl(getenv('FACEBOOK_REDIRECT_URI'), $permissions);
return redirect()->to($loginUrl);
}
public function facebookCallback()
{
$helper = $this->facebook->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
return redirect()->to('/login')->with('error', 'Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
return redirect()->to('/login')->with('error', 'Facebook SDK returned an error: ' . $e->getMessage());
}
if (!isset($accessToken)) {
if ($helper->getError()) {
return redirect()->to('/login')->with('error', "Error: " . $helper->getError() . "\n");
} else {
return redirect()->to('/login')->with('error', 'Bad request');
}
}
// OAuth 2.0 client handler
$oAuth2Client = $this->facebook->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
// Get user info from Facebook
try {
$response = $this->facebook->get('/me?fields=id,name,email', $accessToken);
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
return redirect()->to('/login')->with('error', 'Graph returned an error: ' . $e->getMessage());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
return redirect()->to('/login')->with('error', 'Facebook SDK returned an error: ' . $e->getMessage());
}
$user = $response->getGraphUser();
// Store user data in session or database
$session = session();
$session->set([
'id' => $user['id'],
'name' => $user['name'],
'email' => $user['email'],
'is_logged_in' => true,
]);
return redirect()->to('/dashboard');
}
public function dashboard()
{
$session = session();
$is_logged_in = $session->get('is_logged_in');
if($is_logged_in)
{
$data=array();
$data['name']=$session->get('name');
$data['id']=$session->get('id');
$data['email']=$session->get('email');
return view('dashboard',$data);
}else
return redirect()->to('/login');
}
public function logout()
{
$session = session();
$session->destroy();
return redirect()->to('/login');
}
}
?>
8 Create Index View File
Design the view in app/Views/index.php to include the login button and initiate the Login with Facebook in CodeIgniter process.
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 the URL
http://localhost:8080/index.php/login
13 Conclusion
By following these steps, you can easily implement Login with Facebook in CodeIgniter 4. This method simplifies user authentication by using Login Facebook via Oauth 2.0, providing a seamless experience for users logging into your CodeIgniter 4 application.