Login with Facebook in CodeIgniter


login-with-facebook-in-codeigniter-by-codexworld

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

login-with-facebook-in-codeIgniter-folders-files-structure-by-codexworld

Database Table Creation

To store the user information, you need to create a table into the database. The users table SQL would like the below.

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;

Controllers (User_authentication.php)

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

  • __construct() Load the User model for insert or update the users data into the database.
  • index() Connect with Facebook Graph API, pass the users data to the User model, load the login and profile details view, and pass the users data to the view – all of those functionalities are implemented into this function.
  • logout() This function uses to logout the users from their Facebook account.

You only need to change the $appId, $appSecret, and $redirectUrl variable value according to your Facebook App credentials.

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class 
User_Authentication extends CI_Controller
{
    function 
__construct() {
        
parent::__construct();
        
// Load user model
        
$this->load->model('user');
    }
    
    public function 
index(){
        
// Include the facebook api php libraries
        
include_once APPPATH."libraries/facebook-api-php-codexworld/facebook.php";
        
        
// Facebook API Configuration
        
$appId 'Insert Facebook App ID';
        
$appSecret 'Insert Facebook App Secret';
        
$redirectUrl base_url() . 'user_authentication/';
        
$fbPermissions 'email';
        
        
//Call Facebook API
        
$facebook = new Facebook(array(
          
'appId'  => $appId,
          
'secret' => $appSecret
        
        
));
        
$fbuser $facebook->getUser();
        
        if (
$fbuser) {
            
$userProfile $facebook->api('/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);
            if(!empty(
$userID)){
                
$data['userData'] = $userData;
                
$this->session->set_userdata('userData',$userData);
            } else {
               
$data['userData'] = array();
            }
        } else {
            
$fbuser '';
            
$data['authUrl'] = $facebook->getLoginUrl(array('redirect_uri'=>$redirectUrl,'scope'=>$fbPermissions));
        }
        
$this->load->view('user_authentication/index',$data);
    }
    
    public function 
logout() {
        
$this->session->unset_userdata('userData');
        
$this->session->sess_destroy();
        
redirect('/user_authentication');
    }
}

Models (User.php)

User model contains one function named checkUser(). Using this function, we’ll insert or update the user data into the users database table.

<?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)

This view would be loaded at the time of displaying the login button (before login) and users profile details (after login).

<?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>
    <?php
    
echo '<div class="welcome_txt">Welcome <b>'.$userData['first_name'].'</b></div>';
    echo 
'<div class="fb_box">';
    echo 
'<p class="image"><img src="'.$userData['picture_url'].'" alt="" width="300" height="220"/></p>';
    echo 
'<p><b>Facebook ID : </b>' $userData['oauth_uid'].'</p>';
    echo 
'<p><b>Name : </b>' $userData['first_name'].' '.$userData['last_name'].'</p>';
    echo 
'<p><b>Email : </b>' $userData['email'].'</p>';
    echo 
'<p><b>Gender : </b>' $userData['gender'].'</p>';
    echo 
'<p><b>Locale : </b>' $userData['locale'].'</p>';
    echo 
'<p><b>FB Profile Link : </b>' $userData['profile_url'].'</p>';
    echo 
'<p><b>You are login with : </b>Facebook</p>';
    echo 
'<p><b>Logout from <a href="'.base_url().'user_authentication/logout">Facebook</a></b></p>';
    echo 
'</div>';
    
?>
</div>
<?php ?>

Libraries (facebook-api-php-codexworld/)

Insert the Facebook API PHP SDK folder in the application/libraries directory. You can find the Facebook PHP SDK folder into our downloadable package.

Config (autoload.php)

Load the session and database libraries in autoload.php file.

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

Conclusion

That’s all! Now open the application URL (http://localhost/codeigniter/user_authentication/) on the browser and check the login system with Facebook in CodeIgniter. All files are included into the Download Source Code package, download it and place the files into the CodeIgniter application as per the instructions.

9 Comments

  1. John Said...
    • CodexWorld Said...
  2. Furanki Said...
  3. Furanki Said...
  4. Fawad Said...
  5. Rajkumar Said...
  6. Sahar Said...
  7. Deepak Said...
  8. Benjamin Said...

Leave a reply

Connect With CodexWorld