Using Facebook PHP SDK 3 with CodeIgniter 2.1

To access the Facebook API, there exists the Facebook PHP SDK to simplify the process. I needed Facebook OAuth in one of my projects using CodeIgniter but had some hard time trying to get it done. I faced a lot of errors, the main one though was that: getUser always returns 0. I found out that this is pretty much popular on stackoverflow and other websites – each proposing different solution. In this post, I try to organize all the steps and collect them in one place. References and downloads are provided at the end of the post.

Facebook App

  1. Before starting, make sure you create a new App.
  2. Get the APP ID and APP Secret.
  3. After creating your App, click Edit Settings or Edit App.
  4. In the basic info, add your domain name in the App domain.
  5. In the “select how your app integrates with Facebook” click on website and add the same domain you added in step 4 but with http:// as prefix.
  6. If you want to test locally, try creating a Virtual Host.


  1. Download the Facebook PHP SDK.
  2. Download CodeIgniter.
  3. Extract CodeIgniter.
  4. Extract the Facebook SDK and
    1. Rename facebook.php to Facebook.php
    2. add the following at the beginning of the Facebook.php file right after the php opening tag.
      if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    3. Copy the 3 files in the Facebook SDK extracted directory to application/libraries in CodeIgniter.
  5. In CodeIgniter, create a file facebook.php in application/config directory with the following content (make sure to add your application Id and secret key of the Facebook app):
     $config['appId'] = 'YOUR APP ID';
     $config['secret'] = 'YOUR SECRET KEY';
  6. Open your application/config/config.php file and make sure $config['allow_get_array'] is set to true.

Using OAuth

In OAuth, the procedure is the following:

  1. The user clicks on a sign in link on your website.
  2. User is redirected to Facebook, enter his credentials, authorize your app.
  3. Facebook then redirects the user back to your application with data.

Create a controller, say Main Controller. In your controller’s constructor add the following code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

	public function Main(){
		parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
		$CI = & get_instance();
$config = $CI->config->item('facebook');
$this->load->library('Facebook', $config);

	function index(){
		// Try to get the user's id on Facebook
		$userId = $this->facebook->getUser();

		// If user is not yet authenticated, the id will be zero
		if($userId == 0){
			// Generate a login url
			$data['url'] = $this->facebook->getLoginUrl(array('scope'=>'email'));
			$this->load->view('main_index', $data);
		} else {
			// Get user's data and print it
			$user = $this->facebook->api('/me');



Create a view, called main_index.php in your views directory.

<a href="<?php echo $url; ?>">Click here to login</a>

In the constructor, the parse_str function is called to copy the variables sent by Facebook to the $_REQUEST var so that the Facebook SDK can do its checks. This step is required because CodeIgniter has its own special input class that manipulates $_GET, $_POST, $_COOKIE, and so on. After that, the Facebook configuration is loaded and used to initialize the Facebook SDK (or we can call it the Facebook library by now).

In the index function, we first check whether the user is already authenticated by trying to get his user id. If the id is zero, that means he is not authenticated and we need to authenticate. This is done by generating a link, getLoginUrl(), and passing it to the view so that the user clicks and authenticate. The array passed to the getLoginUrl() specifies the scope. By default, the getLoginUrl() will cause the user to authenticate our application to get only his basic information. In this example, I assume we want his email as well and therefore I pass it as scope to the getLoginUrl() function.

If the user is authenticated, we get the user’s data and print it. You can read more about that here.


Here is the application folder with everything in this post. Click here to download it.


Use GA28994OFF As Coupon while registering to to get 9.94 OFF =D

Liked it? share it.FacebookLinkedInTwitterGoogle+Email

232 thoughts on “Using Facebook PHP SDK 3 with CodeIgniter 2.1

  1. watch ufc 188 free streaming

    Beyond strikes additionally, it has numerous with the features
    you want. Very less of your budget and time is spent in case you choose this alternative of watching TV.
    You won’t need to fight in the handheld remote control to the family TV.
    Basically everyone is not interested inside same notion of movies.

  2. gta 5 online cheats

    com you can find some great games that will amuse for hours.
    Continue to use potato mines as you start to plan sunflowers in the
    water lane. You may set just one ‘macro’ goal such as going undefeated in the current season.

  3. Read Full Report

    Staggeringly enough, this may eventuate to your guy at any quinquennium.

    Other comments included “GOD is arriving back and you also Mr. * Click for the author’s name to look at their profile and articles. Problems concerning terrorism can simply spread derived from one of country to another.

  4. Source

    It’s also easy to build your personal show
    if you wish to complete so. Another bizarre study completed is about the position used from the lavatory.
    Host Rachel Maddow declared Kelly and Fox News simply”made it up. Find Haryana news, Jharkhand news and Hindi News on every topic at jagranpost.

  5. More about the author

    Keeping abreast while using latest Lebanon news happenings will
    be the fastest way to complete so. Other comments included “GOD is originating back therefore you Mr. The newspapers be a significant tool for freedom struggle. For more info as well as see its other cool features, visit:.

  6. next page

    People are migrating for the easier and faster ways of marketing these days.
    If yes then get online, as respond to every such real question is available these days around the internet.

    These innovative machines engage customers, and dramatically reduce overhead costs.
    Most preferred medium of news in India is online Hindi News.

  7. More about the author

    Reporting this information may be the role with the news media outlets.
    For a lot of people each day is incomplete without reading the newspaper.
    Now the same eighths are available at as low as $30, according to your Denver Post on June
    22. In today’s time, you will find numerous websites publishing online news from all over the world.

  8. next page

    3) News media is repeated constantly, often in mind-numbing
    detail, often for trivial topics. In addition, you may upload
    Bollywood masala videos, when you have any interesting video associated
    with a actor. The newspapers turn into a significant tool for freedom
    struggle. There are 2 kinds of machinima news programs: partial and fully animated.

  9. chicken house plans ,next page

    There’s something social an outdoor setting which is alluring.

    Durability means the metal is a bit more resistant against scuffs.
    Moreover the newest stuff first comes at internet so online stores would be the perfect destination for a buy them.
    ve tried using them diets,without much success, though the
    towers and condos worked much better.

  10. Check This Out

    Reporting this information could be the role on the
    news media outlets. Kanchan Kumar Vaidya writes about “
    daily news newspaper , Hindi news portal , Hindi Samachar.

    Host Rachel Maddow declared that Kelly and Fox
    News simply”made it up. Most preferred medium of news in India is online Hindi News.

  11. Get More Information

    In fact, they inform, educate and entertain be involved in nation’s development.
    Article Source: Heaton could be the author informed on Green Engineering.
    The latest news coming our strategy is that each one will not be well between Madhuri
    Dixit and Shri Ram Nene. Newspapers are like a warehouse of information highlighting different segments.

  12. Full Article

    Lean on the doctor along with friendly medical staff you created rapport with.
    Neighbors were shocked that any crime might happen there.

    SADC program has assisted various states inside region organize ICAO audits.
    In today’s time, you will find numerous websites publishing online news from all over the world.

  13. Find Out More

    3) News media is repeated constantly, often in mind-numbing detail, often for trivial topics.
    Read Media Republic News and Press Releases in Cairo, Egypt.
    Lifestyle news and Indian economy news are most demanded sections from
    the news for people. Most preferred medium of news in India is online
    Hindi News.

  14. Click This Link

    (ABC) demonstrated that Huisgenoot, You and Drum are in the top of the their list.
    Another bizarre study completed is about the position used within the lavatory.

    Though you will find those who speak other languages too but mostly Hindi
    is spoken within a large region. says Mahamad El Tanahy,
    Managing Director of Cit – Jo.

  15. Find Out More

    Article Source: i – Phone news and daily news that’s
    all of these advantages stick to the links. Though Mars is
    maraka for Tula Lagna, a rightly conjunct or aspected Mars gives benefic results.
    Therefore using the aid of a newspaper is really a good option.
    There are two kinds of machinima news programs: partial and fully animated.

  16. Recommended Reading

    Here is really a hint about what the newest discoveries
    will unfold in this lifetime. Phoenix News, it truly is limited by Chinese speaking audiences.

    SADC program has assisted various states within the region get ready
    for ICAO audits. You will find these for about $100, but you’ll find
    some web-based programs that you just can use free.

  17. Don

    Thank you for some other informative blog. Where else
    may just I get that kind of information written in such a perfect means?

    I have a undertaking that I’m simply now operating on, and
    I’ve been on the look out for such info.

  18. Jame

    Hi my loved one! I wish to say that this article is amazing, great written and include approximately all
    vital infos. I’d like to look extra posts like this .


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>