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

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

54 thoughts on “Facebook SDK PHP v4 & CodeIgniter”

  1. Thank you very much for this, it works perfectly. After being stucked for a couple of hours, I finally can do something.

    Thx !

  2. I am new for facebook integration. This tutorial is really helpfull for me to know about the integration. But I am a beginner in this so is there any way to find the implementation process for beginners. As here i am not able to find the autoload file mention in at location “libraries/facebook/vendor/autoload.php”.

    1. autoload.php
      <?php
      class Autoloader {
      static public function loader($className) {
      $filename = str_replace('\\', '/', $className) . ".php";

      // echo $filename.'’;

      if ( file_exists($filename) ) {
      include($filename);
      if (class_exists($className)) {
      return TRUE;
      }
      }
      return FALSE;
      }
      }

      spl_autoload_register(‘Autoloader::loader’);

  3. You have a typo in the example usage.

    You say
    $login_url = $this->facebook->get_login_url();
    but it should be
    $login_url = $this->facebook->login_url();

  4. Hey great tutorial. I’m getting this error:

    require_once(application/libraries/facebook/vendor/autoload.php): failed to open stream: No such file or directory

    And I did install composer. Any ideas?

    Thanks!

    1. Fixed the problem with the composer. Had to install it in the application/libraries/facebook folder.

      But now I’m getting this: Unable to load the requested class: facebook

      Any idea?

      Thanks!

  5. I had to change
    “require_once( APPPATH . ‘libraries/facebook/vendor/autoload.php’ );” -> “require_once( APPPATH . ‘libraries/facebook/Facebook/autoload.php’ );”

    Also i got this error:
    Fatal error: Class ‘FacebookFacebookSession’ not found in…

  6. HI. I am getting this error: Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /server_path_to_file/application/libraries/facebook/Facebook.php on line 79

    Any tip for me?

      1. My previous problem was with PHP version. Now I have 5.4 running.

        I was getting the vendor error and I’ve fixed changing

        require_once( APPPATH . ‘libraries/facebook/vendor/autoload.php’ );

        to

        require_once( APPPATH . ‘libraries/facebook/Facebook/autoload.php’ );

        Then I have the following error:

        Fatal error: Cannot redeclare class Facebook in /home/servarpath/application/libraries/facebook/Facebook.php on line 15

        The file Is just a copy and paste from the tutorial.

        What am I doing wrong.

        I am not using composer, I don’t understand it. It is really mandatory to use it? Is the error caused by not using it?

        Thanks for your help.

        1. Another small step. My previous problem was caused by a Controller that was also named Facebook. Thats why I was getting the error that I was declaring 2 Facebook libraries.

          I’ve changed the Controller name to Social and then… another error:

          Fatal error: Class ‘Facebook\FacebookSession’ not found in /home/pathtoserver/public_html/application/libraries/facebook/Facebook.php on line 26

          What am I doing wrong 🙂 I am learning slowly. Hope you can point me the way 😛

          Have a nice day!

  7. Hi again,

    The problem with PHP 5.4 was gone. But still Internal Server Error 500.

    I see in your code (facebook.php):
    // Autoload the required files
    require_once( APPPATH . ‘libraries/facebook/vendor/autoload.php’ );

    but folow the steps, we don’t have this file. I tried to created vendor folder then put this file on it. Do i need to modify something else?

    Many thanks!

  8. I don’t understand about

    require_once( APPPATH . 'libraries/facebook/vendor/autoload.php' );

    Because you didn’t explain that where autoload.php is replaced. I have to change some string like /src/Facebook into /Facebook

    Is this correct?

    1. I would to say thank you. My problem was at wrong url.

      The coborff project was usefull too.

      Now it´s working….

  9. Hey Ben, what’s good?

    I’m just letting you know that I loved your tutorial, and decided to make something to help.
    I have created a Github repository with all the necessary integrations (and some extra stuff)
    Here is the link: Coborff
    I credited your tutorial on the Readme file, and if you wish I may add you as a contributor in case you wanna add stuff or just be recognized as part of the team hahah
    Have a nice day and stay awesome!

  10. Hi Ben, how are you doing?

    I´m trying to make some posts using FacebookBatchRequest without success. Do you have any hint to do this?

    I need to make post into my facebook groups ( let me clear: one post to 5 facebook groups ).

    Thanks in advance

    1. I use this function to post in groups.

      public function post_group($group_id, $message, $link){
      if ( $this->session ){

      $request = ( new FacebookRequest( $this->session, ‘POST’, ‘/’.$group_id.’/feed’,
      array(
      ‘message’=>$message,
      ‘link’=> $link) ) )->execute();
      $results = $request->getGraphObject()->asArray();

      $resultado=$results;

      return $resultado;
      }
      return false;

      }

      This function works fine if I need to post at only one group….if I need to post more than one nok.

      1. I found a solution:

        $corpo_msg=array(
        ‘message’ => $msg,
        ‘link’ => $url,
        ‘picture’ => $url,
        ‘caption’ => ‘Pedido Online’,
        );

        you can put some “posts” here:

        $pub_face[]=array(
        ‘method’ => ‘POST’,
        ‘relative_url’ => “/$id_group/feed”,
        ‘body’ => http_build_query($corpo_msg),
        );

        $publicou = $this->facebook->post_batch($pub_face);

        library:=>

        public function post_batch($params){
        if ( $this->session ){

        $request = (new FacebookRequest($this->session, ‘POST’, null, array(‘batch’ => json_encode($params))))->execute();
        $results = $request->getGraphObject()->asArray();

        return $results;

        }
        return false;

        }

        It´s working!

  11. Im getting an error

    A PHP Error was encountered

    Severity: Error

    Message: Class ‘BaseFacebook’ not found

    Filename: libraries/facebook.php

    Line Number: 25

    Backtrace:

    Please help me out!

  12. hello sir ,

    i am using this library and struggling more then two days.

    my problem is

    Array ( [error] => Array ( [message] => This authorization code has been used. [type] => OAuthException [code] => 100 [fbtrace_id] => GS3VD2zHV27 ) )

    plz help .

  13. I am getting following error message, please help :

    An Error Was Encountered
    Unable to load the requested language file: language/english/facebook_lang.php

  14. please help:

    An uncaught Exception was encountered

    Type: Facebook\FacebookSDKException

    Message: You must provide or set a default application id.

    Filename: F:\xampp\htdocs\fb2\vendor\facebook\php-sdk-v4\src\Facebook\FacebookSession.php

    Line Number: 320

    Backtrace:

    File: F:\xampp\htdocs\fb2\vendor\facebook\php-sdk-v4\src\Facebook\FacebookRedirectLoginHelper.php
    Line: 75
    Function: _getTargetAppId

    File: F:\xampp\htdocs\fb2\application\libraries\facebook\facebook.php
    Line: 113
    Function: __construct

    File: F:\xampp\htdocs\fb2\application\controllers\Welcome.php
    Line: 25
    Function: login_url

    File: F:\xampp\htdocs\fb2\index.php
    Line: 315
    Function: require_once

  15. Is facebook updated API getting message [error] => Array ( [message] => This authorization code has been used. [type] => OAuthException [code] => 100 [fbtrace_id] => GS3VD2zHV27 ) )

Leave a Reply

Your email address will not be published. Required fields are marked *