Use the Facebook API with Codeigniter

The Facebook PHP SDK

Facebook has an  endorsed PHP Facebook API wrapper located here on github.  This library gives the php developer much more intuitive access to the facebook api methods and entities.  It is well documented and complete.

Download (v3.2.0)

Where do I put it?

Place both facebook_base.php and facebook.php in your application/libraries directory

How do I use it?

You can load the facebook sdk one of two ways.

  1. Create a config array and pass it with the loading of the library
    $fb_config = array(
        'appId'  => 'YOUR_APP_ID_HERE',
        'secret' => 'YOUR_APP_SECRET_HERE'
    $this->load->library('facebook', $fb_config);
  2. Create  a config file facebook.php in application/config
    $config['appId']  = 'YOUR_APP_ID_HERE';
    $config['secret'] = 'YOUR_APP_SECRET_HERE';

If you are writing a facebook application and/or will be using the facebook sdk throughout your application, the second option will allow you to add it to your library autoload.

Now what?

Lets re-create the example provided with the sdk to give you a comparison to be able to translate other facebook php-sdk examples to codeigniter friendly semantics.

For comparison, view the stock example.php

Now for the CI version



class Example extends CI_Controller {

    function __construct()

    function index()

        $fb_config = array(
            'appId'  => 'YOUR_APP_ID_HERE',
            'secret' => 'YOUR_APP_SECRET_HERE'

        $this->load->library('facebook', $fb_config);

        $user = $this->facebook->getUser();

        if ($user) {
            try {
                $data['user_profile'] = $this->facebook
            } catch (FacebookApiException $e) {
                $user = null;

        if ($user) {
            $data['logout_url'] = $this->facebook
        } else {
            $data['login_url'] = $this->facebook



    <title>Facebook Sweetness</title>
    <h1>Facebook stuff</h1>

    <?php if (@$user_profile): ?>

            <?php echo print_r($user_profile, TRUE) ?>
        <a href="<?= $logout_url ?>">Logout</a>
    <?php else: ?>
        <h2>Welcome, please login below</h2>
        <a href="<?= $login_url ?>">Login</a>
    <?php endif; ?>