In this tutorial, we will explain to you how to create a login with Facebook using CodeIgniter framework using Facebook PHP SDK. Facebook login is simply an open authentication used to provide access to server data after authorizing a user through a third party.
Before you begin to integrate login with Facebook in CodeIgniter, we need to download the Facebook PHP SDK library and also need Facebook App ID and App Secret.
In this example, we are using the Facebook PHP SDK library in CodeIgniter, this library gives users permission to sign in with their existing Facebook accounts in the Codeigniter application. so we can get the user information from Facebook.
Now we need to app id facebook and App Secret for Facebook login. first, we have to create the Facebook app. so you can see the below steps.

CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oauth_provider` enum('facebook','google','twitter','') COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`picture_url` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`link_url` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
application/config/autoload.php
in this config/autoload.php file, we need to load the library (database and session) and helper(URL). so you can use the below code to load the Codeigniter library and Codeigniter helper.
$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url');
facebook.php
In this file, we have to set configuration variables, so we must specify the App ID, the App secret, and redirect URLs according to the Facebook application credentials.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Facebook API Configuration
| -------------------------------------------------------------------
|
| To get an facebook app details you have to create a Facebook app
| at Facebook developers panel (https://developers.facebook.com)
|
| facebook_app_id string Your Facebook App ID.
| facebook_app_secret string Your Facebook App Secret.
| facebook_login_redirect_url string URL to redirect back to after login. (do not include base URL)
| facebook_logout_redirect_url string URL to redirect back to after logout. (do not include base URL)
| facebook_login_type string Set login type. (web, js, canvas)
| facebook_permissions array Your required permissions.
| facebook_graph_version string Specify Facebook Graph version. Eg v3.2
| facebook_auth_on_load boolean Set to TRUE to check for valid access token on every page load.
*/
$config['facebook_app_id'] = 'Enter_Facebook_App_ID';
$config['facebook_app_secret'] = 'Enter_Facebook_App_Secret';
$config['facebook_login_redirect_url'] = 'facebook_login/';
$config['facebook_logout_redirect_url'] = 'facebook_login/logout';
$config['facebook_login_type'] = 'web';
$config['facebook_permissions'] = array('email');
$config['facebook_graph_version'] = 'v3.2';
$config['facebook_auth_on_load'] = TRUE;
?>
first, we need to create “facebook-php-sdk” directory into the “application/third_party” directory and after go to this directory using the command prompt. download the Facebook PHP SDK library using the below command.
composer require facebook/graph-sdk
application/libraries/Facebook.php
First, we must have to Include the autoload file provided by Facebook PHP SDK in this class library. after then you can easily add login with Facebook functionality using PHP SDK v5 to CodeIgniter application.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Facebook PHP SDK v5 for CodeIgniter 3.x
*
* Library for Facebook PHP SDK v5. It helps the user to login with their Facebook account
* in CodeIgniter application.
*
* This library requires the Facebook PHP SDK v5 and it should be placed in libraries folder.
*
* It also requires social configuration file and it should be placed in the config directory.
*
* @package CodeIgniter
* @category Libraries
* @author XpertPhp
* @license http://xpertphp.com/license/
* @link http://xpertphp.com
* @version 3.0
*/
// Include the autoloader provided in the SDK
require_once APPPATH .'third_party/facebook-php-sdk/vendor/autoload.php';
use Facebook\Facebook as FB;
use Facebook\Authentication\AccessToken;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Helpers\FacebookJavaScriptHelper;
use Facebook\Helpers\FacebookRedirectLoginHelper;
Class Facebook
{
/**
* @var FB
*/
private $fb;
/**
* @var FacebookRedirectLoginHelper|FacebookJavaScriptHelper
*/
private $helper;
/**
* Facebook constructor.
*/
public function __construct(){
// Load fb config
$this->load->config('facebook');
// Load required libraries and helpers
$this->load->library('session');
$this->load->helper('url');
if (!isset($this->fb)){
$this->fb = new FB([
'app_id' => $this->config->item('facebook_app_id'),
'app_secret' => $this->config->item('facebook_app_secret'),
'default_graph_version' => $this->config->item('facebook_graph_version')
]);
}
// Load correct helper depending on login type
// set in the config file
switch ($this->config->item('facebook_login_type')){
case 'js':
$this->helper = $this->fb->getJavaScriptHelper();
break;
case 'canvas':
$this->helper = $this->fb->getCanvasHelper();
break;
case 'page_tab':
$this->helper = $this->fb->getPageTabHelper();
break;
case 'web':
$this->helper = $this->fb->getRedirectLoginHelper();
break;
}
if ($this->config->item('facebook_auth_on_load') === TRUE){
// Try and authenticate the user right away (get valid access token)
$this->authenticate();
}
}
/**
* @return FB
*/
public function object(){
return $this->fb;
}
/**
* Check whether the user is logged in.
* by access token
*
* @return mixed|boolean
*/
public function is_authenticated(){
$access_token = $this->authenticate();
if(isset($access_token)){
return $access_token;
}
return false;
}
/**
* Do Graph request
*
* @param $method
* @param $endpoint
* @param array $params
* @param null $access_token
*
* @return array
*/
public function request($method, $endpoint, $params = [], $access_token = null){
try{
$response = $this->fb->{strtolower($method)}($endpoint, $params, $access_token);
return $response->getDecodedBody();
}catch(FacebookResponseException $e){
return $this->logError($e->getCode(), $e->getMessage());
}catch (FacebookSDKException $e){
return $this->logError($e->getCode(), $e->getMessage());
}
}
/**
* Generate Facebook login url for web
*
* @return string
*/
public function login_url(){
// Login type must be web, else return empty string
if($this->config->item('facebook_login_type') != 'web'){
return '';
}
// Get login url
return $this->helper->getLoginUrl(
base_url() . $this->config->item('facebook_login_redirect_url'),
$this->config->item('facebook_permissions')
);
}
/**
* Generate Facebook logout url for web
*
* @return string
*/
public function logout_url(){
// Login type must be web, else return empty string
if($this->config->item('facebook_login_type') != 'web'){
return '';
}
// Get logout url
return $this->helper->getLogoutUrl(
$this->get_access_token(),
base_url() . $this->config->item('facebook_logout_redirect_url')
);
}
/**
* Destroy local Facebook session
*/
public function destroy_session(){
$this->session->unset_userdata('fb_access_token');
}
/**
* Get a new access token from Facebook
*
* @return array|AccessToken|null|object|void
*/
private function authenticate(){
$access_token = $this->get_access_token();
if($access_token && $this->get_expire_time() > (time() + 30) || $access_token && !$this->get_expire_time()){
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
// If we did not have a stored access token or if it has expired, try get a new access token
if(!$access_token){
try{
$access_token = $this->helper->getAccessToken();
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e->getMessage());
return null;
}
// If we got a session we need to exchange it for a long lived session.
if(isset($access_token)){
$access_token = $this->long_lived_token($access_token);
$this->set_expire_time($access_token->getExpiresAt());
$this->set_access_token($access_token);
$this->fb->setDefaultAccessToken($access_token);
return $access_token;
}
}
// Collect errors if any when using web redirect based login
if($this->config->item('facebook_login_type') === 'web'){
if($this->helper->getError()){
// Collect error data
$error = array(
'error' => $this->helper->getError(),
'error_code' => $this->helper->getErrorCode(),
'error_reason' => $this->helper->getErrorReason(),
'error_description' => $this->helper->getErrorDescription()
);
return $error;
}
}
return $access_token;
}
/**
* Exchange short lived token for a long lived token
*
* @param AccessToken $access_token
*
* @return AccessToken|null
*/
private function long_lived_token(AccessToken $access_token){
if(!$access_token->isLongLived()){
$oauth2_client = $this->fb->getOAuth2Client();
try{
return $oauth2_client->getLongLivedAccessToken($access_token);
}catch (FacebookSDKException $e){
$this->logError($e->getCode(), $e->getMessage());
return null;
}
}
return $access_token;
}
/**
* Get stored access token
*
* @return mixed
*/
private function get_access_token(){
return $this->session->userdata('fb_access_token');
}
/**
* Store access token
*
* @param AccessToken $access_token
*/
private function set_access_token(AccessToken $access_token){
$this->session->set_userdata('fb_access_token', $access_token->getValue());
}
/**
* @return mixed
*/
private function get_expire_time(){
return $this->session->userdata('fb_expire');
}
/**
* @param DateTime $time
*/
private function set_expire_time(DateTime $time = null){
if ($time) {
$this->session->set_userdata('fb_expire', $time->getTimestamp());
}
}
/**
* @param $code
* @param $message
*
* @return array
*/
private function logError($code, $message){
log_message('error', '[FACEBOOK PHP SDK] code: ' . $code.' | message: '.$message);
return ['error' => $code, 'message' => $message];
}
/**
* Enables the use of CI super-global without having to define an extra variable.
*
* @param $var
*
* @return mixed
*/
public function __get($var){
return get_instance()->$var;
}
}
?>
application/controllers/Facebook_login.php
Go to the application/controllers directory and create a new “Facebook_login.php” file.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Facebook_login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('facebook');
$this->load->model('facebook_model');
}
public function index(){
$addData = array();
if($this->facebook->is_authenticated()){
$fbUserData = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email,link,gender,picture');
$addData['oauth_provider'] = 'facebook';
$addData['oauth_uid'] = !empty($fbUserData['id'])?$fbUserData['id']:'';;
$addData['first_name'] = !empty($fbUserData['first_name'])?$fbUserData['first_name']:'';
$addData['last_name'] = !empty($fbUserData['last_name'])?$fbUserData['last_name']:'';
$addData['email'] = !empty($fbUserData['email'])?$fbUserData['email']:'';
$addData['gender'] = !empty($fbUserData['gender'])?$fbUserData['gender']:'';
$addData['picture_url'] = !empty($fbUserData['picture']['data']['url'])?$fbUserData['picture']['data']['url']:'';
$addData['link_url'] = !empty($fbUserData['link'])?$fbUserData['link']:'https://www.facebook.com/';
$userID = $this->facebook_model->checkUser($addData);
if(!empty($userID)){
$data['fbData'] = $addData;
$this->session->set_userdata('fbData', $addData);
}else{
$data['fbData'] = array();
}
$data['logoutURL'] = $this->facebook->logout_url();
}else{
$data['authURL'] = $this->facebook->login_url();
}
$this->load->view('facebook_login',$data);
}
public function logout() {
$this->facebook->destroy_session();
$this->session->unset_userdata('fbData');
redirect('facebook');
}
}
?>
application/models/Facebook_model.php
Go to the application/modelsdirectory and create a new “Facebook_model.php” file.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Facebook_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function checkUser($data = array()){
if(!empty($data)){
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('oauth_provider'=>$data['oauth_provider'], 'oauth_uid'=>$data['oauth_uid']));
$query = $this->db->get();
$total_user = $query->num_rows();
if($total_user > 0){
$result = $query->row_array();
$data['updated_at'] = date("Y-m-d H:i:s");
$update = $this->db->update('users', $data, array('id' => $result['id']));
$userID = $result['id'];
}else{
$data['created_at'] = date("Y-m-d H:i:s");
$data['updated_at'] = date("Y-m-d H:i:s");
$insert = $this->db->insert('users', $data);
$userID = $this->db->insert_id();
}
}
return $userID?$userID:FALSE;
}
}
?>
application/views/facebook_login.php
Go to the application/views directory and create a new “facebook_login.php” file.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login With Facebook Using CodeIgniter</title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Login With Facebook Using CodeIgniter</h2>
<br />
<div class="panel panel-default">
<?php if(!empty($authURL)){ ?>
<a href="<?php echo $authURL; ?>"><img src="<?php echo base_url('assets/images/facebook-login-button.png'); ?>"></a>
<?php }else{ ?>
<div class="panel-heading">Welcome User</div>
<div class="panel-body">
<img class="img-responsive img-circle img-thumbnail" src="<?php echo $fbData['picture_url']; ?>"/>
<p><b>Facebook ID:</b> <?php echo $fbData['oauth_uid']; ?></p>
<p><b>Name:</b> <?php echo $fbData['first_name'].' '.$fbData['last_name']; ?></p>
<p><b>Email:</b> <?php echo $fbData['email']; ?></p>
<p><b>Gender:</b> <?php echo $fbData['gender']; ?></p>
<p><b><a href="<?php echo $logoutURL; ?>">Logout</a></p>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
Read Also
Login with Facebook Account using PHP
Login With Google Account Using PHP