Facebook SDK PHP v5 & CodeIgniter

Written by
Published
Updated
Typical Read
5 minutes

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:

[shell]
composer require facebook/graph-sdk
[/shell]

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

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

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

[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’
);
[/php]

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:

[php]
/*
| ——————————————————————-
| 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’ );
[/php]

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]
<?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;
}
}
[/php]

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:

[php]
$this->facebook->METHOD_NAME();
[/php]

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

[php]
$login_url = $this->facebook->login_url();
[/php]

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

58 comments on “Facebook SDK PHP v5 & CodeIgniter”.

Felipe Pereira

# Apr 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: https://github.com/LipePereira/coborff" rel="nofollow ugc">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!

# Feb 2, 2015

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

Leandro

# Jan 28, 2015

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

# Jan 30, 2015

You’ll need to use Composer to install the dependencies. See https://www.benmarshall.me/facebook-sdk-php-v4/ for more info.

# Jan 19, 2015

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?

# Jan 30, 2015

Use Composer to install the dependencies which includes the autoload.php file. See https://www.benmarshall.me/facebook-sdk-php-v4/ for more info.

Lang

# Jan 16, 2015

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!

# Jan 30, 2015

Use Composer to install the dependencies which includes the autoload.php file. See https://www.benmarshall.me/facebook-sdk-php-v4/ for more info.

# Jan 10, 2015

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?

# Jan 30, 2015

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

# Feb 19, 2015

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.

# Feb 19, 2015

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!

# Jan 3, 2015

Doesn’t work with latest SDK

# Jan 30, 2015

Can you provide a little more info than it doesn’t work? What error are you getting?

# Dec 30, 2014

Does not work for me, FacebookSession does not exist.

# Jan 30, 2015

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

Helge

# Dec 17, 2014

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…

# Jan 30, 2015

Be sure you’re loading that class with: use Facebook\FacebookSession;

Pablo

# Dec 9, 2014

Fixed it. Thanks!

Pablo

# Dec 8, 2014

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!

Pablo

# Dec 9, 2014

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!

# Jan 30, 2015

Take a look at https://www.benmarshall.me/facebook-sdk-php-v4/. I’ve just updated it and provided more detail on installing the SDK.

# Jan 30, 2015

Does that file exist in your project? Take a look at https://www.benmarshall.me/facebook-sdk-php-v4/ for more info on installing the SDK.

Ger

# Dec 3, 2014

Wtf, the vendor folder not exists.

# Jan 30, 2015

You’ll need to use Composer to install the dependencies. See https://www.benmarshall.me/facebook-sdk-php-v4/ for more info on installing the SDK.

Tori

# Dec 1, 2014

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

# Jan 30, 2015

Can you provide me the code you’re using?

Farhan Islam

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

Ali Onder

# Nov 6, 2014

Great article. thanks.

riyas

# Nov 19, 2014

Hi,
I am facing this error,

Fatal error: Class ‘Facebook\FacebookSession’ not found in…..

any idea?

Thanks!

# Jan 30, 2015

Make sure you have use Facebook\FacebookSession. See https://www.benmarshall.me/facebook-sdk-php-v4/ for more info on installing the SDK.

Shylor

# Nov 2, 2014

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

# Nov 18, 2014

Nice catch and thanks, updated!

Jitender

# Oct 28, 2014

where can i find autoload.php

# Feb 2, 2015

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.

# Jan 14, 2017

autoload.php
// echo $filename.'’;

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

spl_autoload_register(‘Autoloader::loader’);

Anurag

# Oct 6, 2014

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

# Feb 2, 2015

You’ll need to install the dependencies for the SDK. Take a look at https://www.benmarshall.me/facebook-sdk-php-v4/, should get you on your way.

Daniyal

# Sep 16, 2014

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

Jean-David

# Sep 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 !

Join the conversation.

Your email address will not be published.

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.