Facebook SDK PHP v4 & CodeIgniter

Trying to get the latest version of Facebook SDK for PHP (v4) working well with CodeIgniter? Me too! After doing a bunch of digging with a lot of trial and error, I finally figured it out. Learn how to build a library for CodeIgniter that will help bridge the gap between it and the Facebook SDK for PHP.

Trying to get the latest version of Facebook SDK for PHP (v4) working well with CodeIgniter? Me too! After doing a bunch of digging with a lot of trial and error, I finally figured it out. Learn how to build a library for CodeIgniter that will help bridge the gap between it and the Facebook SDK for PHP.

Step 1: Download & setup folders

The quickest & simplest way to install the Facebook SDK is via Composer. Installing is as easy as adding a require entry for the Facebook SDK for PHP to the composer.json file in the application directory:

application/composer.json

{
  "require" : {
    "facebook/php-sdk-v4" : "4.0.*"
  }
}

Navigate to the application directory and run composer install to download the required dependencies.

Step 2: Create & define config variables

You’ll also need to setup some config variables by creating a new config file:

application/config/facebook.php

$config['facebook']['api_id']       = 'YOUR APP ID';
$config['facebook']['app_secret']   = 'YOUR APP SECRET';
$config['facebook']['redirect_url'] = 'https://yourdomain.com/login';
$config['facebook']['permissions']  = array(
                                        'email',
                                        'user_location',
                                        'user_birthday'
                                      );

Open the application/config/autoload.php and add the Facebook config file you just created to the Auto-load Config files:

/*
| -------------------------------------------------------------------
|  Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
|	$autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files.  Otherwise, leave it blank.
|
*/

$autoload['config'] = array( 'facebook' );

Step 3: Create the Facebook CodeIgniter library

Create a new file called Facebook.php in the application/libraries directory.

This by no means is a complete library, but shows you how to use the API to create methods enabling you to access them in your controllers.

application/libraries/facebook/facebook.php:

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

// Autoload the required files
require_once( APPPATH . 'vendor/facebook/php-sdk-v4/autoload.php' );

// Make sure to load the Facebook SDK for PHP via composer or manually

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;

class Facebook
{
  var $ci;
  var $session = false;

  public function __construct()
  {
    // Get CI object.
    $this->ci =& get_instance();

    // Initialize the SDK
    FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );
  }

  /**
   * Get FB session.
   */
  public function get_session()
  {
    if ( $this->ci->session->userdata('fb_token') ) {
      // Validate the access_token to make sure it's still valid
      $this->session = new FacebookSession( $this->ci->session->userdata('fb_token') );
      try {
        if ( ! $this->session->validate() ) {
          $this->session = false;
        }
      } catch ( Exception $e ) {
        // Catch any exceptions
        $this->session = false;
      }
    }
    else
    {
      // Add `use Facebook\FacebookRedirectLoginHelper;` to top of file
      $helper = new FacebookRedirectLoginHelper( $this->ci->config->item('redirect_url', 'facebook') );
      try {
        $this->session = $helper->getSessionFromRedirect();
      } catch( FacebookRequestException $ex ) {
        // When Facebook returns an error
        print_r($ex->getResponse());
        //redirect( base_url( 'login?err=' . $ex->getResponse() ) );
      } catch( \Exception $ex ) {
        print_r($ex->getResponse());
        // When validation fails or other local issues
        //redirect( base_url( 'login?err=' . $ex->getResponse() ) );
      }
    }
  }

  /**
   * Login functionality.
   */
  public function login()
  {
    $this->get_session();
    if ( $this->session )
    {
      $this->ci->session->set_userdata( 'fb_token', $this->session->getToken() );

      $user = $this->get_user();

      if ( $user && ! empty( $user['email'] ) )
      {
         $result = $this->ci->user_model->get_user( $user['email'] );

          if ( ! $result )
          {
            // Not registered.
            $this->ci->session->set_flashdata( 'fb_user', $user );
            redirect( base_url( 'register' ) );
          }
          else
          {
            if ( $this->ci->user_model->sign_in( $result->username, $result->password ) )
            {
              redirect( base_url( 'home' ) );
            }
            else
            {
              die( 'ERROR' );
              redirect( base_url( 'login' ) );
            }
          }
      }
      else
      {
        die( 'ERROR' );
      }
    }
  }

  /**
   * Returns the login URL.
   */
  public function login_url()
  {
    // Add `use Facebook\FacebookRedirectLoginHelper;` to top of file
    $helper = new FacebookRedirectLoginHelper( $this->ci->config->item('redirect_url', 'facebook') );

    return $helper->getLoginUrl( $this->ci->config->item('permissions', 'facebook') );
    // Use the login url on a link or button to
    // redirect to Facebook for authentication
  }

  /**
   * Returns the current user's info as an array.
   */
  public function get_user()
  {
    $this->get_session();
    if ( $this->session )
    {
      $request = ( new FacebookRequest( $this->session, 'GET', '/me' ) )->execute();
      $user    = $request->getGraphObject()->asArray();

      return $user;
    }
    return false;
  }

  /**
   * Get user's profile picture.
   */
  public function get_profile_pic( $user_id )
  {
    $this->get_session();
    if ( $this->session )
    {
      $request = ( new FacebookRequest( $this->session, 'GET', '/' . $user_id . '/picture?redirect=false&type=large' ) )->execute();
      $pic     = $request->getGraphObject()->asArray();

      if ( ! empty( $pic ) && ! $pic['is_silhouette'] ) {
        return $pic['url'];
      }
    }
    return false;
  }
}

The library above will give you access to the Facebook SDK Graph API. It creates and saves the Facebook token in session so you can access it later for calls to the API.


Example Usage

Once you’ve loaded the Facebook library you created above, you’ll have access to it within your controllers with the following:

For example, if you wanted to get the login URL (where user’s grant access):

Using the examples above, you should be able to add more methods to the library using the Graph API. If you need any help or run into any problems, drop me a comment below.


More on the Facebook SDK for PHP

Facebook PHP SDK v5.x (4.1) — a complete guide!

Facebook SDK PHP is a powerful library allowing you to retrieve user information, publish to profiles, enable Facebook registrations, logins and more. Learn how to easily implement the Facebook SDK PHP library (v4) with easy to follow examples to get your site integrated quickly.

Implement the Facebook SDK 5.x (4.1) for PHP to enable one-click registrations & logins, gain access to user photos, timelines and even publish to profiles.

Update (April 29, 2015): Facebook PHP SDK 5.x? What happened to 4.1 you ask? The Facebook PHP SDK will start following SemVer starting with v5.0. Before the decision to adopt SemVer, the official Facebook PHP SDK was going to be released as v4.1. But now v4.1 is just an alias to v5.0.0. So any references to 4.1 can be safely aliased to v5.0.0. For more information, see F8 2015 Facebook Developer Conference and the new PHP SDK.

Continue reading “Facebook PHP SDK v5.x (4.1) — a complete guide!”