Using Facebook PHP-SDK 3.x to register/login user with Codeigniter 2.1.0 Using Facebook PHP-SDK 3.x to register/login user with Codeigniter 2.1.0 codeigniter codeigniter

Using Facebook PHP-SDK 3.x to register/login user with Codeigniter 2.1.0


I suggest you read the framework documentation. Adding a library to CodeIgniter is not a hard task. And Facebook library is no exception.

Here's a quick integration I've just come up with:

1.create a config file:application/config/facebook.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');$config['appId'] = 'app_id';$config['secret'] = 'app_secret';

2.place the sdk files in the libraries folder application/libraries/ and rename the facebook.php file to Facebook.php and replace the php tag with this:

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

3.in your controller load the config file and then load the Facebook library:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class Welcome extends CI_Controller {    public function __construct()    {        parent::__construct();        // Your own constructor code        $CI = & get_instance();        $CI->config->load("facebook",TRUE);        $config = $CI->config->item('facebook');        $this->load->library('facebook', $config);    }    public function index()    {        $user = $this->facebook->getUser();        if($user) {            try {                $user_info = $this->facebook->api('/me');                echo '<pre>'.htmlspecialchars(print_r($user_info, true)).'</pre>';            } catch(FacebookApiException $e) {                echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';                $user = null;            }        } else {            echo "<a href=\"{$this->facebook->getLoginUrl()}\">Login using Facebook</a>";        }    }}

Now in the constructor method, you have just initialized the Facebook library (sdk) and it can be accessed by using: $this->facebook.

Notes:

  • You can always use an existing library, just google it
  • A common practice is to extend the core Controller class and add the Facebook library initialization there.
  • Or create another library, extend the Facebook library, load the config file there and then autoload this new library.


After getting the $user, check session parameters with print_r($_SESSION). After that, check some variables by if(isset($_SESSION['some session var'])). If this condition is true, then navigate to your main page with header("location:main.php"); exit;


You can try using my extension http://github.com/deth4uall/Facebook-Ignited it is set up to work with Facebook. Just update the config file and it will allow you to do what you need to do, as well as some additional methods that I added myself.