Facebook Login for Website in codeigniter

Facebook Login for Website in codeigniter

Facebook login for website using facebook api

Why Facebook login for website ?

          Nowadays Website users are not interested in regitration using manually filling form.one click registration or sign up process is helps to get more subscribers and followers  to your website. facebook web login is very fast and powerfull way to one click facebook website login. Facebook is most popular  social platform and many users have an account of facebook. facebook web login allows users to sign up facebook account for website using their logged in facebook account

Create Facebook API

To access Facebook API you need to create a Facebook developers account and specify the facebook api ID & facebook api Secret at the time of calling the Facebook API. 

Follow the below steps to create facebook api id’s using facebook developers account.

  1. Go to the Facebook for facebook Developers page and sign in facebook account.
  2. click the add new app in my apps link at the top of navigation bar.
  3. enter some basic details such as display name and email id
  4. Create  App Id Button
  5. go to dashboard click settings >> Basic page >> Specify app domains >> choose website category
  6. and save all changes
  7. select app platform as web.
  8. enter redirect url and save.
  9. Go to the Settings » Basic page, note the facebook api ID and facebook api Secret.
  10. This facebook api ID and facebook api secret allow you to access the Facebook API.

 

Facebook SDK for PHP

  • The facebook graph api sdk contains the latest version (v5) of Facebook SDK for PHP. 
  •  you can download it from github and other facebook graph api or facebook sdk resources.

Database for facebook login for website

CREATE TABLE `fb_users` (
  `id` int(11) NOT NULL,
  `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` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `link` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


ALTER TABLE `fb_users`
  ADD PRIMARY KEY (`id`);


ALTER TABLE `fb_users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

controller in facebook login for website

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 
class User_Authentication extends CI_Controller { 
    function __construct() {
        parent::__construct(); 
        // Load facebook oauth library 
        $this->load->library('facebook');
        // Load user model 
        $this->load->model('user');
    }
     
    public function index(){ 
        $userData = array(); 
            // Authenticate user with facebook 
            if($this->facebook->is_authenticated()){
            // Get user info from facebook
            $fbUser = $this->facebook->request('get', '/me?fields=id,first_name,last_name,email,link,gender,picture'); 
            // Preparing data for database insertion 


            $userData['oauth_provider'] = 'facebook';
            $userData['oauth_uid']      = !empty($fbUser['id'])?$fbUser['id']:''; 
            $userData['first_name']     = !empty($fbUser['first_name'])?$fbUser['first_name']:''; 
            $userData['last_name']      = !empty($fbUser['last_name'])?$fbUser['last_name']:''; 
            $userData['email']          = !empty($fbUser['email'])?$fbUser['email']:''; 
            $userData['gender']         = !empty($fbUser['gender'])?$fbUser['gender']:''; 
            $userData['picture']        = !empty($fbUser['picture']['data']['url'])?$fbUser['picture']['data']['url']:''; 
            $userData['link']           = !empty($fbUser['link'])?$fbUser['link']:'https://www.facebook.com/'; 


             $fname=!empty($fbUser['first_name'])?$fbUser['first_name']:'';
             $lname=!empty($fbUser['last_name'])?$fbUser['last_name']:'';
             $f_id=!empty($fbUser['id'])?$fbUser['id']:'';
             $f_profile=!empty($fbUser['picture']['data']['url'])?$fbUser['picture']['data']['url']:'';
             $f_gender=!empty($fbUser['gender'])?$fbUser['gender']:'';
             $f_email=!empty($fbUser['email'])?$fbUser['email']:'';

             $profile=!empty($fbUser['picture']['data']['url'])?$fbUser['picture']['data']['url']:'';
                
            // Insert or update user data to the database 
            $userID = $this->user->checkUser($userData);
             
            // Check user data insert or update status 
            if(!empty($userID)){ 
                $data['userData'] = $userData; 
                 
                // Store the user profile info into session 
                $this->session->set_userdata('userData', $userData);
                $this->session->set_userdata('fname', $fname);
                $this->session->set_userdata('lname', $lname);
                $this->session->set_userdata('f_id', $f_id);
                $this->session->set_userdata('f_profile', $f_profile);
                $this->session->set_userdata('f_gender', $f_gender);
                $this->session->set_userdata('f_email', $f_email);
                // $this->session->set_userdata('profile', $profile);  
            }else{
               $data['userData'] = array();
            } 
            // Facebook logout URL 
            $data['logoutURL'] = $this->facebook->logout_url();
        }else{ 
            // Facebook authentication url 
            $data['authURL'] =  $this->facebook->login_url(); 
        } 
         
        // Load login/profile view 
        // $this->load->view('eitalyon/header',$data);
        $this->load->view('index',$data);
        // $this->load->view('eitalyon/footer',$data);s

        // $this->load->view('eitalyon/header',$data); 
        // $this->load->view('eitalyon/index',$data); 
        // $this->load->view('eitalyon/footer',$data); 

    } 
 


    public function logout(){ 
        // Remove local Facebook session
        $this->facebook->destroy_session();
        // Remove user data from session 
        $this->session->unset_userdata('userData');
        $this->session->unset_userdata('fname');
        $this->session->unset_userdata('lname');
        $this->session->unset_userdata('f_id');
        $this->session->unset_userdata('f_profile'); 
        $this->session->unset_userdata('f_gender');
        $this->session->unset_userdata('f_email');

        // Redirect to login page 
        if (!$this->session->userdata('fname')){
            redirect('login');
        }
        
    } 
}?>

Model in Facebook login for website

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Model {
    function __construct() {
        $this->tableName = 'fb_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();
            $prevCheck = $prevQuery->num_rows();
            
            if($prevCheck > 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 for facebook login for website



<!-- CSS only -->


<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<div style="background-color: #508bfc;">
    

 <br>
    <center><h2 style="color: White;">Login With Facebook in Codeigniter.</h2>
    <p>Add This Code To your codeigniter Framework</p>
    </center>
<section class="vh-100" style="background-color: #508bfc;">
   
  <div class="container py-5 h-100">
    <div class="row d-flex justify-content-center align-items-center h-100">
      <div class="col-12 col-md-8 col-lg-6 col-xl-5">
        <div class="card shadow-2-strong" style="border-radius: 1rem;">
          <div class="card-body p-5 text-center">

            <h3 class="mb-5">Sign in</h3>

            <div class="form-outline mb-4">
              <input type="email" id="typeEmailX-2" class="form-control form-control-lg" />
              <label class="form-label" for="typeEmailX-2">Email</label>
            </div>

            <div class="form-outline mb-4">
              <input type="password" id="typePasswordX-2" class="form-control form-control-lg" />
              <label class="form-label" for="typePasswordX-2">Password</label>
            </div>

            <!-- Checkbox -->
            <div class="form-check d-flex justify-content-start mb-4">
              <input class="form-check-input" type="checkbox" value="" id="form1Example3" />
              <label class="form-check-label" for="form1Example3"> Remember password </label>
            </div>

            <button class="btn btn-primary btn-lg btn-block" type="submit">Login</button>

            <hr class="my-4">

         
            <a href="<?php echo $authURL; ?>" class="btn btn-lg btn-block btn-primary mb-2" style="background-color: #3b5998;"
              type="submit"><i class="fab fa-facebook-f me-2"></i>Sign in with facebook</a>

          </div>
        </div>
      </div>
    </div>
  </div>
</section>

</div>

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top