Facebook SDK PHP v5 & CodeIgniter

53 Comments

Join the Conversation

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. Amna
    at 4:11 am

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

  2. suman
    at 1:50 am

    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

  3. suman
    at 1:36 am

    I am getting following error message, please help :

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

    • suman
      at 1:50 am

      created a lang file, fixed.

  4. at 10:22 am

    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 .

  5. at 6:33 am

    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!

  6. at 8:40 am

    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

    • at 8:48 am

      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.

      • at 3:19 pm

        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!

  7. Rincy Renin
    at 3:51 am

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

  8. Felipe Pereira
    at 1:06 pm

    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!

    • Luís Cláudio
      at 8:35 am

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

      The coborff project was usefull too.

      Now it´s working….

  9. Leandro
    at 10:24 am

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

  10. at 8:27 pm

    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?

  11. Lang
    at 12:52 am

    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!

  12. at 5:23 pm

    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?

    • at 10:13 am

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

      • at 5:57 pm

        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.

        • at 6:08 pm

          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!

    • at 10:21 am

      Be sure you’re loading that class with: use Facebook\FacebookSession; and have the necessary dependencies included.

  13. Helge
    at 10:31 am

    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…

  14. Pablo
    at 11:01 pm

    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!

  15. Tori
    at 4:06 am

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

  16. Farhan Islam
    at 9:46 am

    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.

  17. Shylor
    at 2:13 am

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

    • at 12:57 am

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

  18. Anurag
    at 2:13 pm

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

  19. Jean-David
    at 9:34 am

    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

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

All comments are held for moderation. I'll publish all comments that are 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.

%d bloggers like this: