Facebook SDK PHP v5 & 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 (v5) working well with CodeIgniter? Lucky for you, that’s what this article is all about! I’ll go over how to build a library for CodeIgniter that will help bridge the gap between CI and the Facebook SDK for PHP.

Facebook SDK PHP & CodeIgniter Libraries

Why a library? Simply put libraries are perfect to maintain separation between your local resources and the global framework resources.

Step 1. Download Facebook SDK PHP v5

The quickest & simplest way to install the Facebook SDK is via Composer. Running the following command in the application directory:

composer require facebook/graph-sdk

If you already have a composer.json file and want to specify the version of the SDK you’d like to install, add a require entry:

application/composer.json

{
  "require" : {
    "facebook/graph-sdk" : "5.7.*"
  }
}

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

Step 2. Define application variables

Create a new config file in application/config for your Facebook-specific variables. This will hold your Facebook application credentials:

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']['callback']     = 'https://yourdomain.com/fb-callback';
$config['facebook']['permissions']  = array(
                                        'email',
                                        'user_location',
                                        'user_birthday'
                                      );

Next, you’ll need to tell CI to load the config file. Do this by opening the application/config/autoload.php file and add the following:

/*
| -------------------------------------------------------------------
|  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.

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

class Facebook {
  var $ci;
  var $accessToken;
  var $fb;

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

    $this->fb = new \Facebook\Facebook([
      'app_id' => $this->ci->config->item('app_secret', 'api_id')',
      'app_secret' => $this->ci->config->item('app_secret', 'facebook'),
      'default_graph_version' => 'v2.10',
      //'default_access_token' => '{access-token}', // optional
    ]);
  }

  /**
   * Get FB session.
   */
  public function get_access_token() {
    $helper = $this->fb->getRedirectLoginHelper();

    try {  
      $this->accessToken = $helper->getAccessToken();  
    } catch( Facebook\Exceptions\FacebookResponseException $e ) {  
      // When Graph returns an error  
      echo 'Graph returned an error: ' . $e->getMessage();  
      exit;  
    } catch( Facebook\Exceptions\FacebookSDKException $e ) {  
      // When validation fails or other local issues  
      echo 'Facebook SDK returned an error: ' . $e->getMessage();  
      exit;  
    }  
  }

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

      $user = $this->get_user();

      if ( $user && !empty( $user->getProperty( 'email' ) ) ) {
         $result = $this->ci->user_model->get_user( $user->getProperty( '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() {
    $helper = $this->fb->getRedirectLoginHelper();

    return $helper->getLoginUrl( $this->ci->config->item( 'callback', 'facebook' ), $this->ci->config->item( 'permissions', 'facebook' ) );
  }

  /**
   * Returns the current user's info as an array.
   */
  public function get_user() {
    $user = false;

    $this->get_access_token();
    if ( $this->get_access_token ) {
      try {
        // Get the Facebook\GraphNodes\GraphUser object for the current user.
        // If you provided a 'default_access_token', the '{access-token}' is optional.
        $response = $this->fb->get( '/me?fields=id,name,email,first_name,last_name,birthday,location,gender', $this->get_access_token );
      } catch( Facebook\Exceptions\FacebookResponseException $e ) {
        // When Graph returns an error
        echo 'ERROR: Graph ' . $e->getMessage();
        exit;
      } catch( Facebook\Exceptions\FacebookSDKException $e ) {
        // When validation fails or other local issues
        echo 'ERROR: validation fails ' . $e->getMessage();
        exit;
      }
    }
    
    return $response->getGraphUser();
  }

  /**
   * Get user's profile picture.
   */
  public function get_profile_pic( $user_id ) {
    $user = $this->get_user();

    if ( $user ) {
      $fbID = $me->getProperty( 'id' );

      return '//graph.facebook.com/' . $fbID . '/picture?type=large';
    }

    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:

$this->facebook->METHOD_NAME();

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

$login_url = $this->facebook->login_url();

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

Comments

  1. Alexandre June 25, 2019

    And another typo here :

    if($user && ! empty( $user->getProperty(’email’) ) {

    You forgot to close the third parenthesis.

    Just my view but your code will be a lot more clear using if/endif and to stop adding white space everywhere, like your “! empty (” instead of “!empty(”
    White space should be used to separate entities and order. Just my view.

    • Good catch, updated!

      • i think facebook/graph-sdk was upgrade, the autoload folder inst in ‘vendor/facebook/php-sdk-v4’ , but is in ‘/vendor/facebook/graph-sdk/src/Facebook’

        • anyway , i still have a problem, can you help me:

          An uncaught Exception was encountered
          Type: Facebook\Exceptions\FacebookSDKException

          Message: Required “app_id” key not supplied in config and could not find fallback environment variable “FACEBOOK_APP_ID”

          Filename: C:\wamp64\www\novo\carteira\vendor\facebook\graph-sdk\src\Facebook\Facebook.php

          Line Number: 139

          Backtrace:

          File: C:\wamp64\www\novo\carteira\application\libraries\Facebook.php
          Line: 21
          Function: __construct

          File: C:\wamp64\www\novo\carteira\index.php
          Line: 315
          Function: require_once

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

  3. 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

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

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

  5. 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 .

  6. Muaaz Khalid March 30, 2017

    Facebook has updated the API to v5

  7. 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!

  8. 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

    • 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.

      • 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!

  9. Rincy Renin May 19, 2016

    how to run composer install to download the required dependencies. in codeigniter 3

  10. Felipe Pereira April 11, 2015

    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!

  11. Take a look at https://www.benmarshall.me/facebook-sdk-php-v4/ for more info on installing the SDK. Sounds like you don’t have the dependencies required.

    • Luís Cláudio May 4, 2015

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

      The coborff project was usefull too.

      Now it´s working….

  12. I had downloaded the sdk php v4, but this file (vendor/autoload.php) is not included =/

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

  14. 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!

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

    • Sounds like you’ve got some malformed code. Double check and make sure you have all the appropriate opening and closing brackets.

      • 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.

        • 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!

  16. Doesn’t work with latest SDK

  17. Does not work for me, FacebookSession does not exist.

  18. 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…

  19. Fixed it. Thanks!

  20. 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!

  21. Wtf, the vendor folder not exists.

  22. i loged in fb and accept app. but get_user() alway return false. Please help me ?

  23. Farhan Islam November 27, 2014

    Nice article.

    I believe you forgot to write i.e. PHP 5.4 is the minimum requirement for this code.

    Between nice step by step writing.

  24. Great article. thanks.

  25. 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();

  26. where can i find autoload.php

    • Take a look at https://www.benmarshall.me/facebook-sdk-php-v4/. You’ll need to install the dependencies first with Composer if your using autoload.php.

    • 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’);

  27. 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”.

  28. If you could create a GitHub repos that would be great 🙂

  29. Jean-David September 5, 2014

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

    Thx !

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

All comments are held for moderation and only published when on topic and not rude. You'll even get little stars if you do an extra good job.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.

icon-search icon-link