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.
Published
Updated
Typical Read
5 minutes
Sponsored
Do you run a development agency, freelance developer or offer website services. Contact me today for information about advertising.
Find your next web developer job
jobs by Indeed

Facebook SDK PHP v5 & CodeIgniter was originally published on Jun 5, 2014 and has recently been updated on Aug 6, 2020 to reflect emerging trends.

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

Did you find Facebook SDK PHP v5 & CodeIgniter useful? Get articles in your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Latest Job Postings
Posted on Aug 9, 2020 at 9:17pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 9:15pm
Full-time
Los Angeles
Posted on Aug 9, 2020 at 1:19am
Littleton, CO
jobs by Indeed
Sponsored
Need help with website, a boost in ranking or online marketing? Contact me today for a free quote.
Sponsored
Do you have a great article to share you want to contribute? Contact me about your idea.
Sponsored
Need help with website, a boost in ranking or online marketing? Contact me today for a free quote.
Sponsored
Need help with website, a boost in ranking or online marketing? Contact me today for a free quote.
Sponsored
Need help with website, a boost in ranking or online marketing? Contact me today for a free quote.

58 Comments on “Facebook SDK PHP v5 & CodeIgniter”

Ravindu Dharmasena

# Jun 6, 2020

You have a typo in application/config/facebook.php. The line

$config[‘facebook’][‘api_id’] = ‘YOUR APP ID’;

should be corrected as the line given below

$config[‘facebook’][‘app_id’] = ‘YOUR APP ID’;

Alexandre

# Jun 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.

# Jun 25, 2019

Good catch, updated!

# Aug 10, 2019

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’

# Aug 10, 2019

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

Amna

# Sep 13, 2017

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

suman

# May 5, 2017

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

Faysal Jawwad

# Aug 7, 2017

Did you find the solution??

suman

# May 5, 2017

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

# May 5, 2017

created a lang file, fixed.

# Apr 4, 2017

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 .

Muaaz Khalid

# Mar 30, 2017

Facebook has updated the API to v5

# Jul 15, 2016

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!

# May 22, 2016

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

# May 22, 2016

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.

# May 23, 2016

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!

Rincy Renin

# May 19, 2016

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

Leave a Reply

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

All comments posted on 'Facebook SDK PHP v5 & CodeIgniter' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

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.