Login with Facebook in CodeIgniter


Integrate Facebook login is the most used feature for today’s web application. Login with Facebook feature helps users to log into the web application easily. Which means that your web application receives more users / customers. We’ve already published Login with facebook using PHP that will help you to implement Facebook login in PHP. In this tutorial, we’re going to explain how to integrate Facebook login in CodeIgniter using Facebook PHP SDK with Facebook Graph API.

Before you begin to implement Facebook login in CodeIgniter 3 using SDK v5, create a Facebook app in Facebook developers panel and get the App ID and App Secret. You should need to set Site URL that would be the same of user authentication controller URL (http://localhost/codeigniter/user_authentication/). Also need to specify the Redirect URL, App ID, and App Secret in your script at the time of connecting with Facebook Graph API.

Once your Facebook app creation is completed, copy the App ID and App Secret and put them into the respective variable in your script.

Take a look on files structure of Login with Facebook in CodeIgniter using PHP SDK v5.

login-with-facebook-codeIgniter-sdk-folders-files-structure-codexworld

Database Table Creation

To store the Facebook profile information, you need to create a table into the database. The following SQL creates a users table with some required fields in MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `picture_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `profile_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config

autoload.php
The database and session libraries are needed, it will better to specify these libraries in the autoload.php file.

$autoload['libraries'] = array('session','database');

facebook.php
Facebook App and API configuration variables are defined in this file. You need to specify the App Id, App Secret and redirect URLs according to your Facebook App 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_type           string   Set login type. (web, js, canvas)
|  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_permissions          array    Your required permissions.
|  facebook_graph_version        string   Specify Facebook Graph version. Eg v2.6
|  facebook_auth_on_load         boolean  Set to TRUE to check for valid access token on every page load.
*/
$config['facebook_app_id']              = 'InsertAppId';
$config['facebook_app_secret']          = 'InsertAppSecret';
$config['facebook_login_type']          = 'web';
$config['facebook_login_redirect_url']  = 'user_authentication';
$config['facebook_logout_redirect_url'] = 'user_authentication/logout';
$config['facebook_permissions']         = array('email');
$config['facebook_graph_version']       = 'v2.6';
$config['facebook_auth_on_load']        = TRUE;

Controllers (User_authentication.php)

User_Authentication controller contains three functions, __construct(), index(), and logout().

  • __construct() – The Facebook library and User model are loaded in this method.
  • index() – The following functionalities are implemented in this method.
    • Connect with Facebook Graph API using the Facebook library, pass the user profile information to the User model for insert into the database.
    • Pass the user data to the view and load the profile details view for authenticated user.
    • Load the login view for the non-authenticated user.
  • logout() – This method destroys the Facebook session, remove the user data from session and logout the user from their Facebook account.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
User_Authentication extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
// Load facebook library
        
$this->load->library('facebook');
        
//Load user model
        
$this->load->model('user');
    }
    public function 
index(){
        
$userData = array();
        
// Check if user is logged in
        
if($this->facebook->is_authenticated()){
            
// Get user facebook profile details
            
$userProfile $this->facebook->request('get''/me?fields=id,first_name,last_name,email,gender,locale,picture');
            
// Preparing data for database insertion
            
$userData['oauth_provider'] = 'facebook';
            
$userData['oauth_uid'] = $userProfile['id'];
            
$userData['first_name'] = $userProfile['first_name'];
            
$userData['last_name'] = $userProfile['last_name'];
            
$userData['email'] = $userProfile['email'];
            
$userData['gender'] = $userProfile['gender'];
            
$userData['locale'] = $userProfile['locale'];
            
$userData['profile_url'] = 'https://www.facebook.com/'.$userProfile['id'];
            
$userData['picture_url'] = $userProfile['picture']['data']['url'];
            
// Insert or update user data
            
$userID $this->user->checkUser($userData);
            
// Check user data insert or update status
            
if(!empty($userID)){
                
$data['userData'] = $userData;
                
$this->session->set_userdata('userData',$userData);
            }else{
               
$data['userData'] = array();
            }
            
// Get logout URL
            
$data['logoutUrl'] = $this->facebook->logout_url();
        }else{
            
$fbuser '';
            
// Get login URL
            
$data['authUrl'] =  $this->facebook->login_url();
        }
        
// Load login & profile view
        
$this->load->view('user_authentication/index',$data);
    }
    public function 
logout() {
        
// Remove local Facebook session
        
$this->facebook->destroy_session();
        
// Remove user data from session
        
$this->session->unset_userdata('userData');
        
// Redirect to login page
        
redirect('/user_authentication');
    }
}

Libraries

Facebook.php
The Facebook class helps to integrate Facebook PHP SDK v5 in CodeIgniter 3.x application. Using this Facebook library, you can easily add the login with Facebook functionality using PHP SDK v5 to the 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 facebook configuration file and it should be placed in the config directory.
 *
 * @package     CodeIgniter
 * @category    Libraries
 * @author      CodexWorld
 * @license     http://www.codexworld.com/license/
 * @link        http://www.codexworld.com
 * @version     2.0
 */

// Include the autoloader provided in the SDK
require_once 'facebook-php-sdk/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;
    }
}

facebook-php-sdk/
Facebook PHP SDK is used to connect with the Facebook Graph API and integrate login system with Facebook. The facebook-php-sdk/ directory contains the latest version (v5) of Facebook SDK for PHP.

Models (User.php)

User model contains one function called checkUser(), it is used to insert or update the user profile information into the database.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model{
    function 
__construct() {
        
$this->tableName 'users';
        
$this->primaryKey 'id';
    }
    public function 
checkUser($data = array()){
        
$this->db->select($this->primaryKey);
        
$this->db->from($this->tableName);
        
$this->db->where(array('oauth_provider'=>$data['oauth_provider'],'oauth_uid'=>$data['oauth_uid']));
        
$prevQuery $this->db->get();
        
$prevCheck $prevQuery->num_rows();
        
        if(
$prevCheck 0){
            
$prevResult $prevQuery->row_array();
            
$data['modified'] = date("Y-m-d H:i:s");
            
$update $this->db->update($this->tableName,$data,array('id'=>$prevResult['id']));
            
$userID $prevResult['id'];
        }else{
            
$data['created'] = date("Y-m-d H:i:s");
            
$data['modified'] = date("Y-m-d H:i:s");
            
$insert $this->db->insert($this->tableName,$data);
            
$userID $this->db->insert_id();
        }

        return 
$userID?$userID:FALSE;
    }
}

Views (user_authentication/index.php)

If the user already logged in with their Facebook account, this view will display the profile details, otherwise, Facebook login button will be shown.

<?php
if(!empty($authUrl)) {
    echo 
'<a href="'.$authUrl.'"><img src="'.base_url().'assets/images/flogin.png" alt=""/></a>';
}else{
?> <div class="wrapper"> <h1>Facebook Profile Details </h1> <div class="welcome_txt">Welcome <b><?php echo $userData['first_name']; ?></b></div> <div class="fb_box"> <p class="image"><img src="<?php echo $userData['picture_url']; ?>" alt="" width="300" height="220"/></p> <p><b>Facebook ID : </b><?php echo $userData['oauth_uid']; ?></p> <p><b>Name : </b><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p> <p><b>Email : </b><?php echo $userData['email']; ?></p> <p><b>Gender : </b><?php echo $userData['gender']; ?></p> <p><b>Locale : </b><?php echo $userData['locale']; ?></p> <p><b>You are login with : </b>Facebook</p> <p><a href="<?php echo $userData['profile_url']; ?>" target="_blank">Click to Visit Facebook Page</a></p> <p><b>Logout from <a href="<?php echo $logoutUrl?>">Facebook</a></b></p> </div> </div> <?php ?>

Conclusion

That’s all! Now run the application OAuth URL (http://localhost/codeigniter/user_authentication/) on the browser and check the login system with Facebook in CodeIgniter. We’ve used the latest version of SDK, so, Facebook PHP SDK v5 library is required. All files including Facebook PHP SDK v5 are included into the Source Code package, download it and place the files into the CodeIgniter application as per the instructions.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

30 Comments

  1. Azad Said...
  2. Salman Said...
  3. Ranjeet Said...
    • CodexWorld Said...
  4. Shravankumar Patil Said...
  5. Tedi Said...
  6. Tedi Said...
    • CodexWorld Said...
  7. KashmirX Said...
  8. Wildan Mukafi Said...
  9. Abdulahad Said...
    • CodexWorld Said...
  10. Amit Said...
  11. Prashant Jaiswal Said...
  12. Harshit Vaid Said...
  13. Rama Aju Said...
    • CodexWorld Said...
  14. Bashir Said...
    • CodexWorld Said...
  15. Karan Said...
  16. John Said...
    • CodexWorld Said...
  17. Furanki Said...
  18. Furanki Said...
  19. Fawad Said...
  20. Rajkumar Said...
  21. Sahar Said...
  22. Deepak Said...
  23. Benjamin Said...

Leave a reply