Facebook & CodeIgniter – Definitive Guide

I spent more hours than the expected starting a simple development for a new Facebook application that runs on top of CodeIgniter. First I read A LOT, then I checked for solutions and, of course, I read a little bit more. After several hours reading and coding I knew it wasn’t good at all so I decided to start a new integration method from the scratch using only the code I found as guide. Here’s the result:

0. Environment

Before you get excited just review a few things before spent time reading another useless post :-)

  • PHP Version 5.2.6
  • MySQL 5 (It doesn’t affect Facebook integration at all but it is good to know)
  • HostMonster is my hosting provider (it is not a marketing initiative, just they have a nice environment set up for PHP)
  • Facebook platform 5 – I upload a copy of it to ensure you get the same copy I used.
  • CodeIgniter 1.6.3 – latest version available at the time of this post.

1. Do not hack CodeIgniter

I found a lot of solutions about hacking CodeIgniter by overriding functions or classes. NO, YOU DO NOT HAVE TO DO IT.

2. Install facebook library as plugin

  • Download the facebook platform ZIP
  • Unzip the files wherever you want -outside your Code Igniter application
  • Copy the WHOLE content under /php folder (under means files inside the folder and not with the container folder) to yout ./system/plugins folder inside Code Igniter application -Note: Yes, you have to include the jsonwrapper folder.
  • Rename the facebook.php file to facebook_pi.php

It is done! You already have installed facebook framework as plugin.

3. Autoload facebook plugin [optional]

To avoid the need of including the “load plugin” sentence inside every controller/class you can modify the ./system/config/autoload.php to include facebook plugin as required. It is almost a requirement for Facebook applications. Add to your $autoload['plugin'] array the facebook plugin. It could look like this:

$autoload['plugin'] = array('facebook');

Note: If you skip this step you will have to include the following line every time you need facebook functionality available.

$this->load->plugin('facebook');

4. Setup your application [updated]

Update your configuration file and set the ./system/application/config/config.php and change it as follows:

$config['uri_protocol'] = "PATH_INFO";
$config['base_url'] = "APPLICATION_URL";

Note: If you want to test your application locally, you can set base_url to http://127.0.0.1/path_to_your_app/

5. Extend your Controller class

Because I’m building a 100% facebook application, all my controllers require facebook API available. So I decided to extend my main Controller class as follows – BTW: By the date of this post the CodeIgniter documentation WAS WRONG about how to extend the core classes (CodeIgniter User Guide Version 1.6.3 – Creating Core System Classes). It is not true -i.e. it is false- that you have to extend the CI_ClassName. At least it didn’t work for me at all. Extend the ClassName directly.

Facebook Controller class should be placed under ./system/application/libraries folder.

Filename: XX_Controller.php (where “XX_” is the prefix you set on your ./system/application/config/config.php file – subclass_prefix parameter)

class FB_Controller extends Controller {
 
	// Facebook application key
	var $API_KEY = 'YOUR_API_KEY';
 
	var $facebook;
	var $uid;
 
	/*
	 * Custom Controller constructor.
	 * Adds Facebook support.
	 *
	 */
	function FB_Controller() {
 
		parent::Controller();
 
		// Authentication key
		$secret = 'YOUR_SECRET_KEY'; 
 
		// Prevent the 'Undefined index: facebook_config' notice from being thrown.
		$GLOBALS['facebook_config']['debug'] = NULL;
 
		// Create a Facebook client API object.
		$this->facebook = new Facebook($this->API_KEY, $secret);
		$this->uid = $this->facebook->require_login();
	}
}

Note: Inside the facebook application I built I always require an authenticated users, so that’s why I do have the require_login() call. However you can also validate if the user already have the application added. You should do this manually inside controller classes because there are a few exceptions where it is needed that user is authenticated but without adding the application.

6. Create your own controllers

Now you can extend your controllers from your Custom Controller. Note: You do not have to add any include or require sentence in your other classes, CodeIgniter will load directly your XX_Controller.php file -if it doesn’t load please check the config.php file and validate the subclass_prefix parameter.

Below you will find an example of a Controller that will validate if the user has the application added in his/her profile.

class Welcome extends XX_Controller {
 
	function Welcome() {
 
		parent::XX_Controller();
 
		// Check if the application has been added by the user
		try {
			if (!$this->facebook->api_client->users_isAppAdded()) {
				$this->facebook->redirect($this->facebook->get_add_url());
				return;
			}
		}
		catch (Exception $x) {
			// Clear cookies for your application and redirect them to a login prompt
			$this->facebook->expire_session();
			$facebook->redirect($this->facebook->get_login_url());
		}
	}
 
	// You should place your Controller's methods below.
 
}

7. Get out and celebrate

CodeIgniter is running as cleaner as you expected and Facebook API was included nicely!

I hope you find this post useful as I said at the beginning.

  PHP Client Library (34.3 KiB, 1,455 hits)



46 Responses to “Facebook & CodeIgniter – Definitive Guide”

iel on December 17th, 2008 1:53 am:

thanks. I’m trying to build my own facebook apps now and your guidelines is very helpful.

Btw, just for fun…could u share your facebook’s apps?


Alberto Dominguez, PMP on December 19th, 2008 10:09 am:

Sure. BTW: I just built the backend, so the creative and flash/AS development aren’t my fault :-) -if you know what I meant.

Davivienda Racking Car


Bayou on December 30th, 2008 11:06 pm:

How about “The URI you submitted has disallowed characters” ? I got this error message in my facebook application. Is there any solutions?


Alberto Dominguez, PMP on January 2nd, 2009 2:22 pm:

It could be a lot of things. Something I’ve learned during my development process is that you probably will have two kind of request: those that will print something into the screen and those that will print something that you will need inside your Flash application.

The first type of request will print something as part of the facebook presentation page. For example: The “sent to /share with your friends”, “the application addition confirmation”, and the “game” itself. The second one will be -in my case- plain XML files that will be used by the Flash game, so I do not have to include any facebook presentation-layer function.

In my opinion you can use a good sniffer or traffic monitor tool as Tamper Data or HTTPFox as a plugin of your Firefox browser so you can see what are you calling, and what the response is.

Hope it helps you.


Shayan on January 23rd, 2009 1:58 am:

Hi,
i must say tht this is a really great article..it explains how to do things Properly..
but i have sum problems in setting it up and hope u can help me..i think i m missing sumthing..m not sure wat callback url is to be set in facebook app..i hav follow your instructions and when i create a controller (testcontroller.php) as:

class Testcontroller extends FB_Controller {
function Test() {
parent::FB_Controller();
}
function index()
{
echo ‘Hello World!!’;
}
}

then, after accessing it in facebook canvas page, it seems to be stuck in lots of post backs loop.
my current callback url is http://127.0.0.1/fbtest/index.php/testcontroller/

kindly help me..
thanx,
regards,
Shayan.


Shayan on January 23rd, 2009 2:15 am:

few more details of wat i m doing..
i hav set base url in codeigniter equal to the base url of my local php server.
http://127.0.0.1/fbtest/

also, in facebook, when i m setting the callback url pointing to a class which is not extended from FB_Controller, e.g. http://127.0.0.1/fbtest/index.php/welcome (i hav not modified welcome.php file)
then it is displaying welcome page correctly in canvas page..also, now when i directly call my custom controller (testcontroller) by typing http://127.0.0.1/fbtest/index.php/testcontroller in my browser, then its working fine that is it 1st redirect me to facebook login n once i have loged in, it redirects me to the welcome page..
but how can i use facebook functoinality? :(
i wud b pleased for ur help..
regards,
shayan..


Alberto Dominguez, PMP on January 23rd, 2009 9:34 am:

You should publish your application to a public domain. You cannot test it from your internal 127.0.0.1 (nor localhost), so your callback URL should be accessible from anywhere. If you do not have a public domain, I will recommend you dynamic DNS services like DynDNS or No IP.


Shayan on January 24th, 2009 6:19 am:

Hi,
the prob was solved.. :)
it was not a public domain or localhost issue..i think my prob was that, when the facebook authentication was completing, it was redirecting to the call back URL (which was, in my case, http://127.0.0.1/fbtest/index.php/testcontroller/) but FB also appending session values in query string (as m using iframe) which CI do not understand (it consider segments of the URL as ‘controller’/'function’/'parameter’ ..and there is no controller such as “?auth_token=8545975…” etc.)

now, i hav modified the FB_Controller slightly, i.e. after

$GLOBALS['facebook_config']['debug'] = NULL;

// i hav added the following code:
parse_str($_SERVER['QUERY_STRING'],$_GET);

// Create a Facebook client API object.
//remaining code is same..

also, i hav modified system/application/config/config.php file (change uri_protocol from “AUTO” to “PATH_INFO”), i.e.

$config['uri_protocol'] = “PATH_INFO”;

..and everything is working fine now.. :)

Note:
i hav follwoing settings for testing..
call back URL : http://127.0.0.1/fbtest/
base_url : http://127.0.0.1/fbtest/
default_controller : ‘Testcontroller’

again, thanks alot Alberto for providing such a nice article which really gets things going..

regards,
Shayan.


Alberto Dominguez, PMP on January 24th, 2009 9:21 am:

I’m glad you found the solution. Thanks for sharing it with all of us.


Alberto Dominguez, PMP on April 7th, 2009 8:51 pm:

The application was mentioned on the largest economic magazine in Colombia – http://www.dinero.com/noticias-caratula/facebook-aprovechelo-negocios/58402.aspx



New Facebook Connect Library For CodeIgniter Released on May 29th, 2009 10:42 am:

[...] and it’s extremely useful. While I’ve implemented the widely used FB_Controller (found here) for Facebook platform applications, I haven’t implemented Connect with CodeIgniter prior to [...]


New Facebook Library For CodeIgniter Released | Blog YODspica Ltd on May 30th, 2009 9:03 pm:

[...] library that will get you up and running in under 5 minutes.  The widely used FB_Controller (found here) for Facebook platform applications, in 7 quick steps you can have a demo Facebook Connect enabled [...]



Lenguajes X » Crear aplicaciones Facebook con CodeIgniter on June 8th, 2009 6:02 am:

[...] Facebook & CodeIgniter – Definitive Guide [...]


Crear aplicaciones Facebook con CodeIgniter « Think Free – Linux.Php.Java.ME.Movies on June 8th, 2009 6:07 am:

[...] Facebook & CodeIgniter – Definitive Guide [...]


Usando CodeIgniter para crear aplicaciones en Facebook | ¡No Quiero Programar! on June 8th, 2009 9:15 am:

[...] IT Project Management – Facebook & CodeIgniter – Definitive Guide [...]


Usando CodeIgniter para Facebook - ..:: Tips para todos ::.. on June 15th, 2009 9:16 am:

[...] IT Project Management – Facebook & CodeIgniter – Definitive Guide [...]


» CodeIgniter: Aplicaciones para Facebook on June 25th, 2009 7:15 am:

[...] Facebook & CodeIgniter – Definitive Guide [...]


carlospaulino on August 12th, 2009 10:20 am:

Segui tu guía, pero algo anda mal, ya que cuando voy a mi aplicacion se queda en un loop infinito

Me podrias ayudar?


Alberto Dominguez, PMP on August 12th, 2009 4:42 pm:

Hola Carlos, creo que debes revisar el URL del callback, es muy probable que ese sea el error. Una opción simple para arreglar el problema es hacer override de la url publica con el archivo etc/hosts o bien checa los comentarios de este post. Si encuentras la razón me cuentas y actualizo el artículo. :-)


carlospaulino on August 12th, 2009 6:04 pm:

El loop lo está ocurriendo cuando llamo $this->facebook->require_login(); si lo quito todo funciona bien. El problema es que la aplicación que estoy escribiendo requiere autentificación ya que debe postear en el wall del usuario.
Hice una pequeña prueba sin usar el codeigniter y pude trabajar perfectamente con la clase de facebook, no obstante el fin es usar CI.
Quiero que me confirmes algo.
En el config tengo

$config['base_url'] = DIRECCIONAPP
$config['uri_protocol']= “PATH_INFO”; (Si no lo uso así me da un problema de que no entiende el requested uri)

Hay algo mal?


carlospaulino on August 12th, 2009 6:05 pm:

Acaso debo cambiar el ‘base_url’ a algo como apps.facebook.com/applicationname, o lo dejo con la direccion de la aplicacion http://direccionapp


Alberto Dominguez, PMP on August 12th, 2009 7:47 pm:

Carlos, mientras hace pruebas en tu equipo puedes usar de Callback algo como “localhost/appname” o “127.0.0.1/appname” dependiendo de la dirección local que usas en tu equipo o en el servidor de pruebas.


Facebook & CodeIgniter – Definitive Guide | Software Production Management on August 27th, 2009 5:39 am:

[...] post: Facebook & CodeIgniter – Definitive Guide | Software Production Management Share and [...]


Javier Ortiz on September 3rd, 2009 12:42 pm:

Hola Alberto

Yo trabajé contigo por allá en el 2004. Después de como media hora de leer y ver los comentarios dije…a este tipo lo conozco…. jejeje. Estoy pasando el core de mis aplicaciones a CodeIgniter y esto me ha servido mucho. Ya había visto la app de Davivienda y pues mira quien estaba detrás. El link de mi app, es http://apps.facebook.com/futbol_colombia, a veces molesta porque se quedó corta de servidor…

Gracias.


Alberto Dominguez, PMP on September 4th, 2009 7:46 pm:

Javier, que bueno saber que le sirvió el artículo. Este mundo definitivamente es muy pequeño! Ojalá todo quede funcionando con FutbolColombia. Mucha suerte, y ya sabe donde me puede encontrar!


Joey Beltran on September 23rd, 2009 12:07 pm:

Hi,

Thank you so much for this wonderful guide.

BTW: I checked your FB app but found this -> Fatal error: Class ‘CI_Controller’ not found in ************ on line *

I purposely hashed (****) the directory so it won’t appear here all the time.


Alberto Dominguez, PMP on September 23rd, 2009 8:20 pm:

Joey, thanks for your comment. The app that inspired this post wasn’t properly removed – keep in mind I developed the backend but I do not manage the application.


helloworlder on November 4th, 2009 5:54 pm:

Thanks Alberto for the article! It helped a lot :-)

And also thanks Shayan for the IFRAME fix.


Frank on November 25th, 2009 12:23 am:

Alberto,

Thanks for the article; it was very helpful for quickly setting up an environment to start building Facebook applications.

Regarding your comments: “the CodeIgniter documentation WAS WRONG about how to extend the core classes (CodeIgniter User Guide Version 1.6.3 – Creating Core System Classes). It is not true -i.e. it is false- that you have to extend the CI_ClassName. At least it didn’t work for me at all. Extend the ClassName directly.”

… well, that’s only partially correct. For the purposes of this article, yes, you should extend Controller rather than CI_Controller. But in general, if you’re extending the core classes, you should look in system/libraries to see what the name of the class actually is. I’m working with version 1.7.2, and every class in system/libraries is prefixed with “CI_”, except for Controller and Model.

I’m not sure why the naming convention was changed for these two classes, but it is what it is. I hope my comment will clear this up for anyone who was confused.


Alberto Dominguez, PMP on November 27th, 2009 7:56 pm:

Frank, thanks a lot. About the naming convention, you are right, I do not have a clear understanding why using CI doesn’t work, maybe for newer versions the thing have changed.


luci3n on December 13th, 2009 9:35 am:

I tried for an iframe facebook app and the uri_protocol parameter PATH_INFO worked only partialy during authorization use ORIG_PATH_INFO. Hope this helps someone. :-)


Steven on December 14th, 2009 2:11 am:

In your controller, users_isAppAdded() is giving an error and Facebook says it’s deprecated. It should be changed to users_isAppUser()


Alberto Dominguez, PMP on December 14th, 2009 5:52 pm:

I have not a lot of free time lately (as you can see I do not write too often). However I will try to upgrade the Guide to use the FB Connect API


Steven on December 14th, 2009 9:05 pm:

I’m working on my first facebook app with codeigniter and so far everything seems to be working ok. The only error I’ve run into was the users_isAppAdded and that was easy enough to find and fix.


gevork on January 1st, 2010 9:58 pm:

I tried all. CI 1.7.2 Instead of canvas, with your example the code is redirected to the path url…

:( (


Aplicaciones Facebook usando CodeIgniter | Economia y finanzas on January 7th, 2010 5:01 pm:

[...] Facebook & CodeIgniter – Definitive Guide Facebook Connect CodeIgniter Library [...]


Kapil Jadhav on February 3rd, 2010 11:00 pm:

I tried your way step by step, the application is called from facebook but it gives a 404 error. Code seems as it should be. How do I debug the FB_Controller or my Welcome controller extending FB_Controller. Has anyone encountered such a problem?


Crear aplicaciones Facebook con CodeIgniter « Not For Default on March 1st, 2010 6:09 pm:

[...] Facebook & CodeIgniter – Definitive Guide [...]



pishty on March 16th, 2010 9:20 am:

Hello guys,

i have added the code given below
route.php
$config['base_url']=”http://apps.facebook.com/signmeup_emv/”;
$config['uri_protocol'] = “PATH_INFO”;

controllers/welcome.php

function Welcome()
{
parent::Controller();
$this->load->model(‘Usercreds_model’);
$this->load->helper(‘form’);
$this->load->helper(‘url’);
$this->load->plugin(‘facebook’);
$GLOBALS['facebook_config']['debug'] = NULL;
$this->facebook = new Facebook($this->__fbApiKey, $this->__fbSecret);
$this->userID = $this->facebook->require_login();
$this->resultStatus=$this->Usercreds_model->getUserCreds($this->userID);
parse_str($_SERVER['QUERY_STRING'],$_GET);
}

however i am getting into an error page

The page isn’t redirecting properly

This problem can sometimes be caused by disabling or refusing to accept cookies.

any help would be very much appreciated


Harvey on May 15th, 2010 3:18 am:

Hello everyone. I have developped another Facebook Connect library, maybe more complete, with also a helper for codeigniter.
You can find it here : http://blog.ebuildy.com/2010/05/13/facebook-connect-pour-codeigniter.html


Alberto Dominguez, PMP on May 16th, 2010 9:32 pm:

Harvey, great news, you should try to translate your article to english :-)


Tecnología y negocios » Aplicaciones Facebook usando CodeIgniter on June 17th, 2010 11:58 am:

[...] Facebook & CodeIgniter – Definitive Guide Facebook Connect CodeIgniter Library [...]


sunil kumar on July 8th, 2010 5:53 am:

Hi

i am developing a facebook app using CI.

will you please suggest me how to use facebook ajax in CI.

Thanks in advance


Leave a Reply

(required)

(required)