Login with facebook using codeigniter - Mostlikers

27 April, 2015

Login with facebook using codeigniter

Hi Guys, Today we are going to see How to log in and registration with Facebook CodeIgniter. Most of the website following Facebook login, Because users get bored to do fill form information, they must like to register and log in by using they social application like Facebook, Twiter, Linkedin, google+. Most of they social media share users basic information by using SDK.    

Login with facebook using codeigniter


Live demo                 Download

So, Facebook is a popular social media. We can exchange our information to some other website with our permission. In this post, I have explained about Login with facebook using CodeIgniter. here I am using facebook SDK to get access user information to store database and get the user details.

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  

Create sample Facebook user table in your database.
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 2.0

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

Path : applications/config/facebook.php

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

After getting the facebook access token data it will store database. If that user had already registered get the user information store on session redirect to a profile page.

* 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









32 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. Replies
    1. First check the facebook api response.

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

    ReplyDelete
  8. session is not expiring even after logout?

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

      Delete
  10. 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
  11. Hello,

    I am getting user id as 0

    Any olution

    ReplyDelete
  12. 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
  13. now i am facing
    We are unable fetch your facebook information.

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

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

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

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

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

    ReplyDelete