Login with facebook using codeigniter - Mostlikers

27 April, 2015

Login with facebook using codeigniter

In this tutorial, We are going to discuss. How to create a login system step by step using Facebook API in CodeIgniter. Here I have used the latest version facebook SDK 5 for access the users token. Follow the step by step process and Create your own facebook login API.
Login with facebook using codeigniter


Live demo                 Download

Before using this script first read our latest tutorial, How to create facebook API. Because it must require for the developer for setting facebook API process.

For better understand how this code will work. Just download this script paste in your localhost. Change the facebook configuration setting. But make sure if you're running this script your app should be in developer mode,

Facebook App

You have to create an application on facebook. After creating app Facebook will provide your application app id and app secret id.

  • Create a new website app
  • Go App review makes it live configuration.
  • Get App ID and App Key
  • Download latest SDK file

Database  

Here I have created 'facebook_user' table for storing facebook user basic information like(email, name,f_id). If the same user login again no need to check every time API response. 
CREATE TABLE IF NOT EXISTS `facebook_user` (
`id` int(11) NOT NULL,
  `email` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `f_id` int(11) NOT NULL
)


Facebook SDK 5.0

Download Facebook SDK file Create new file config folder facebook.php add below code that file.

Create File Path : applications/config/facebook.php (This file contains the facebook API configuration)

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

$config['facebook_app_id']              = '**********************';
$config['facebook_app_secret']          = '**********************';
$config['facebook_login_type']          = 'web';
$config['facebook_login_redirect_url']  = 'welcome/web_login';
$config['facebook_logout_redirect_url'] = 'welcome/logout';
$config['facebook_permissions']         = array('public_profile', 'publish_actions', 'email');
$config['facebook_graph_version']       = 'v2.6';
$config['facebook_auth_on_load']        = TRUE;


Controller (facebook login welcome home page)

Create a new controller for accessing login code. Here I have created a welcome controller.

Path : applications/controllers/welcome.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class welcome extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        // Load library and url helper
        $this->load->library('facebook');
        $this->load->helper('url');
        $this->load->model('users_model','users'); 

    }

    // ------------------------------------------------------------------------

    /**
     * Index page
     */
    public function index()
    {
        $this->load->view('login');
    }

    // ------------------------------------------------------------------------

    /**
     * Web redirect login example page
     */
    public function web_login()
    {
        $data['user'] = array();

        // Check if user is logged in
        if ($this->facebook->is_authenticated())
        {
            // User logged in, get user details
            $user = $this->facebook->request('get', '/me?fields=id,name,
                email,birthday,gender,picture');
            if (!isset($user['error']))
            {
                $data['user'] = $user;
                  $user_information  = array(
                    'name'    => $user["name"],
                    'email'   => $user["email"],
                    'gender'  => $user["gender"],
                    'birthday' => date("Y-m-d",strtotime($user['birthday'])),
                    'log_mode' => 'facebook'
                );
                echo '<pre>'; print_r($user); exit;  
            }

        }
        else 
        {
            echo 'We are unable fetch your facebook information.'; exit;
        }

        // display view
    }

    // ------------------------------------------------------------------------

    
    public function logout()
    {
        $this->facebook->destroy_session();
        redirect('welcome/index');
    }
}

Facebook email id permission

In case you didn't get any email id. Use below code.
$user = $this->facebook->api('/me'); 
           (to)
$user = $this->facebook->api('/me?fields=email,first_name,last_name');

View

Create login.php in view folder add below code.
Path: applications/views/login.php
<body>
<div id="container">
    <h1>Login with facebook</h1>
    <div id="body"> 
    <h2>Welcome to home page</h2>   
    <a href="<?php echo $this->facebook->login_url(); ?>">
     <img src="<?php echo base_url(); ?>resource/images/facebook.png">
    </div>
</div>
</body>



* Remove index.php from your URL sometimes it makes the problem.

http://www.mostlikers.com/2015/05/codeigniter-remove-indexphp-in-url.html



"Once you replace negative thoughts with positive ones, you'll start having positive results."
                                             
                                         - Willie Nelson









39 comments:

  1. i will bee glad if you provide twitter also ?
    thanks

    ReplyDelete
    Replies
    1. is it possible to make it become one table between login facebook and twitter ?

      Delete
    2. Yes is it possible. Create login_type colum enaum ('fb','twit') users table. Store the user information based on fb,twitter

      Delete
    3. Hi bro after research your blog just insert new user, how about users already insert it ? where should i check first !

      Delete
    4. Check this line if(!$this -> users ->count_all_results('f_id',$user['id']))

      Delete
  2. Hello again bro, first of all thanks for making this actually i'm not checking your file i just search and search then i came back again !


    let me tell you my pain based on you script ya ?


    $this->load->model('user_model','users'); //it seems like alias ya ?

    then you use your model as users, am i right ? please correct then


    your model
    {
    parent::__construct();
    $this -> table = 'facebook_user';
    $this->primary_key='id';
    $this -> result_mode = 'object';
    }


    actually what this model ?


    did you want to make all become easy to proses all data in databse ya ?


    piuh so hard to handle this lah

    Thanks man, my pain still keep on !

    when the script login and logout with twitter ?


    LOL to mush request and asking, forgive me



    ReplyDelete
  3. bro how can i just use default model in codeignter ? so hard use your model in my script, i'm not familiar with your model, how can i use default model in codiegnter, what should remove and how tpo fix with simple model, thanks a lot

    ReplyDelete
  4. Hi, thanks ! am using your code. But insertion is not happening. It redirect to the login same page after the facebook sign in.

    ReplyDelete
  5. hi how do i implement this script in hmvc ? also how do i i direct my own button to this script?

    ReplyDelete
    Replies
    1. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

      Delete
  6. It shows me error like Invalid App ID: 0

    ReplyDelete
  7. session is not expiring even after logout?

    ReplyDelete
  8. Replies
    1. Make sure your app id have access to email permission. Or change the latest versions sdk file.

      Delete
  9. it is working fine but it is show user name and id , i want email id
    how will find out.

    thank u


    ReplyDelete
    Replies
    1. Just change few line.

      $user = $this->facebook->api('/me');

      (to)
      $user = $this->facebook->api('/me?fields=email,first_name,last_name');

      Delete
  10. Hello,

    I am getting user id as 0

    Any olution

    ReplyDelete
  11. Hello i have an issue when i click on login with facebook button it redirect me to welcome/web_login?code=********** etc and getting Error 404.

    ReplyDelete
    Replies
    1. * Please check the class name of welcome.php file. web_login() not there in welcome.php file so that is the reason your getting this message.

      Delete
  12. now i am facing
    We are unable fetch your facebook information.

    ReplyDelete
  13. Check you site_url() you must need to add index.php remove htaccess

    ReplyDelete
  14. i have many time subscribe but did't download code

    ReplyDelete
    Replies
    1. Free subscription https://app.box.com/s/8u4dzotaev24e6mmymt1lnrvo5fo14pu

      Delete
  15. Hi, my website uses codeigniter 2.2.1, is it possible to implement the facebook sdk 5?

    ReplyDelete
  16. Hi, my website using codeigniter 2.2.1, is it possible to use facebook sdk 5?

    ReplyDelete
  17. Hi karthick..thanks in advance for your script..some time i get this error Array ( [error] => 2500 [message] => An active access token must be used to query information about the current user. )..what happened there..?

    ReplyDelete
  18. hi karthick..thanks in advance for your script..my code is working for a bit and suddenly i got this error..Array ( [error] => 2500 [message] => An active access token must be used to query information about the current user. )..what wrong with me..?

    ReplyDelete
  19. sir ur demo is not woring??? why

    ReplyDelete
  20. hi i'm using same method as you have used but its not authenticating it directly goes to the else conditions were i struck i donno thanks advance

    ReplyDelete
    Replies
    1. Due to the data security, Facebook has updated new SDK version.

      Delete