Login with Facebook in CodeIgniter using JavaScript SDK

Facebook JavaScript SDK provides the easiest way to implement login system with Facebook on the website. Using JavaScript SDK, you can allow the user to sign into the web application with their Facebook account. The user can log in to your web application using their existing Facebook account without registration on your website.

Various SDK and API are available to integrate Facebook login on the website. But Facebook JavaScript SDK is the most user-friendly way to integrate Facebook login in the web application. It allows you to implement login with Facebook without page refresh using JavaScript SDK. In this tutorial, we will show you how to integrate login with Facebook in CodeIgniter using JavaScript SDK and Graph API.

The following functionalities will be implemented to implement Facebook Login in CodeIgniter.

  • Authenticate the user with the Facebook account using JavaScript SDK.
  • Retrieve user’s profile information using Graph API.
  • Store the user’s profile data in the MySQL database.

Facebook Apps Creation

To access Facebook JavaScript SDK you need to create a Facebook App and specify the App ID on your API call. To generate App ID on Facebook Developer account, go through this step-by-step guide – How to Create Facebook App, App ID, and App Secret

After creating the Facebook App, copy the App ID and put it into the respective option of the init() function in JavaScript code.

Create Database Table

To store the user’s Facebook profile data, a table needs to be created in the database. The following SQL creates a users table with some basic fields in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `cover` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `link` 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;

Login with Facebook using JavaScript SDK

Controller (Facebook_login.php)

The Facebook_Login controller contains 3 functions, __construct(), index(), and saveUserData().

  • __construct() – Loads the User model.
  • index() – Load the login and profile view.
  • saveUserData() – This method is called by the Ajax to insert the user data in the database.
    • Decode the posted JSON data and get user profile data.
    • Insert or update user data in the database using the User model.
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class 
Facebook_Login extends CI_Controller {
    function 
__construct() {
        
parent::__construct();
        
// Load user model
        
$this->load->model('user');
    }
    
    public function 
index(){
        
// Load login & profile view
        
$this->load->view('facebook_login/index');
    }

    public function 
saveUserData() {
        
// Decode json data and get user profile data
        
$postData json_decode($_POST['userData']);
        
        
// Preparing data for database insertion
        
$userData['oauth_provider'] = $_POST['oauth_provider'];
        
$userData['oauth_uid']         = $postData->id;
        
$userData['first_name']     = $postData->first_name;
        
$userData['last_name']         = $postData->last_name;
        
$userData['email']             = $postData->email;
        
$userData['gender']         = $postData->gender;
        
$userData['locale']         = $postData->locale;
        
$userData['cover']             = $postData->cover->source;
        
$userData['picture']         = $postData->picture->data->url;
        
$userData['link']             = $postData->link;
        
        
// Insert or update user data
        
$userID $this->user->checkUser($userData);
        
        return 
true;
    }
}

Model (User.php)

The User model contains 2 functions, __construct() and checkUser().

  • __construct() – Define table name and primary key of this table.
  • checkUser() – Insert or update the user profile information in the users table.
    • If data exist with same oauth_provider and oauth_uid, existing record is updated. Otherwise, the user data is inserted in the users table.
    • Based on the insertion, the respective user ID is returned.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model{
    function 
__construct() {
        
$this->tableName 'users';
        
$this->primaryKey 'id';
    }
    
    
/*
     * Insert / Update facebook profile data into the database
     * @param array the data for inserting into the table
     */
    
public function checkUser($userData = array()){
        if(!empty(
$userData)){
            
//check whether user data already exists in database with same oauth info
            
$this->db->select($this->primaryKey);
            
$this->db->from($this->tableName);
            
$this->db->where(array('oauth_provider'=>$userData['oauth_provider'], 'oauth_uid'=>$userData['oauth_uid']));
            
$prevQuery $this->db->get();
            
            if(
$prevQuery->num_rows() > 0){
                
$prevResult $prevQuery->row_array();
                
                
//update user data
                
$userData['modified'] = date("Y-m-d H:i:s");
                
$update $this->db->update($this->tableName$userData, array('id'=>$prevResult['id']));
                
                
//get user ID
                
$userID $prevResult['id'];
            }else{
                
//insert user data
                
$userData['created']  = date("Y-m-d H:i:s");
                
$userData['modified'] = date("Y-m-d H:i:s");
                
$insert $this->db->insert($this->tableName,$userData);
                
                
//get user ID
                
$userID $this->db->insert_id();
            }
        }
        
        
//return user ID
        
return $userID?$userID:FALSE;
    }
}

View (facebook_login/index.php)

This view displays the Facebook Login button if the user not logged in with their Facebook account, otherwise, the user’s profile data will be shown.

JavaScript Code:
The jQuery Ajax is used to post user’s profile data to the Facebook_Login controller, so, include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

The following JavaScript handles the Facebook authentication process using Facebook JavaScript SDK and Graph API. You need to specify the Facebook App ID in appId option of FB.init() method.

  • fbLogin() – Opens a login dialog to log in with Facebook account.
  • getFbUserData() – Retrieve the user profile data from Facebook and display profile details and login status to the user. This profile information is retrieved from Facebook – Account ID, First Name, Last Name, Email, Gender, Locale, Profile Picture, Cover Photo, and Profile Link.
  • saveUserData() – Post Facebook profile data to saveUserData method of the Facebook_Login controller via Ajax.
  • fbLogout() – Logs the user out from the Facebook account.
<script>
window.fbAsyncInit = function() {
    // FB JavaScript SDK configuration and setup
    FB.init({
      appId      : '1609295222731026', // FB App ID
      cookie     : true,  // enable cookies to allow the server to access the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v2.10' // use graph api version 2.10
    });
    
    // Check whether the user already logged in
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            //display user data
            getFbUserData();
        }
    });
};

// Load the JavaScript SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Facebook login with JavaScript SDK
function fbLogin() {
    FB.login(function (response) {
        if (response.authResponse) {
            // Get and display the user profile data
            getFbUserData();
        } else {
            document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
        }
    }, {scope: 'email'});
}

// Fetch the user profile data from facebook
function getFbUserData(){
    FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture,cover'},
    function (response) {
        document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
        document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
        document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
        document.getElementById('userData').innerHTML = '<div style="position: relative;"><img src="'+response.cover.source+'" /><img style="position: absolute; top: 90%; left: 25%;" src="'+response.picture.data.url+'"/></div><p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p><p><b>Profile Link:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';
        
        // Save user data
        saveUserData(response);
    });
}

// Save user data to the database
function saveUserData(userData){
    $.post("<?php echo base_url('facebook_login/saveUserData'); ?>", {oauth_provider:'facebook', userData: JSON.stringify(userData)}, function(data){ return true; });
}

// Logout from facebook
function fbLogout() {
    FB.logout(function() {
        document.getElementById('fbLink').setAttribute("onclick","fbLogin()");
        document.getElementById('fbLink').innerHTML = '<img src="<?php echo base_url('assets/images/fblogin.png'); ?>"/>';
        document.getElementById('userData').innerHTML = '';
        document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
    });
}
</script>

HTML Code:
The following HTML is used to display the Facebook Login button, user profile data, and login status.

<!-- Display login status -->
<div id="status"></div>

<!-- Facebook login or logout button -->
<a href="javascript:void(0);" onclick="fbLogin();" id="fbLink"><img src="<?php echo base_url('assets/images/fblogin.png'); ?>"/></a>

<!-- Display user profile data -->
<div id="userData"></div>

Login with Facebook using PHP

Conclusion

Our example code makes the Facebook Login integration easier for CodeIgniter web application. It helps to implement Facebook Login in CodeIgniter without page refresh using JavaScript SDK. Only some minimal settings are needed to integrate login system with Facebook on your CodeIgniter application. Alternatively, you can use PHP SDK v5 for CodeIgniter to integrate Facebook login in CodeIgniter.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

5 Comments

  1. Abhimanu Said...
  2. Dsp Said...
  3. Neemata Said...
  4. Aditi Verma Said...
  5. Amit Shee Said...

Leave a reply

keyboard_double_arrow_up