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.

Installing

  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):
     <?php
     $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(){
		parent::__construct();
		parse_str( $_SERVER['QUERY_STRING'], $_REQUEST );
		$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$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');
			print_r($user);
		}
	}

}

?>

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.

Download

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

References

http://stackoverflow.com/questions/9454238/using-facebook-php-sdk-3-x-to-register-login-user-with-codeigniter-2-1-0

http://stackoverflow.com/questions/4478525/is-there-proper-codeigniter-library-to-work-with-facebook-php-sdk

https://developers.facebook.com/docs/reference/php/

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

Liked it? share it.FacebookLinkedInTwitterGoogle+Email

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

  1. Javaid Ahmad

    Dear Friend:
    Thanks after a long search and wasting of my 7 to 10 days i got your article and its amazing Thanks Once agains
    Regards,
    JAVAID AHMAD
    Software enginner and Software archeticts

    Reply
  2. Pingback: GAE not support PHP cURL, so how should we implement Facebook SDK on our application? « 牛頓工作室 NewtonStudio

  3. google authorship wordpress

    Today, I went to the beach front with my kids. I found a sea shell and gave it to
    my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and
    screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

    Reply
  4. Gregory

    I see you share interesting things here, you can earn some extra money, your
    blog has big potential, for the monetizing method, just type in google – K2 advices how to
    monetize a website

    Reply
  5. Prank Video

    Spot on with this write-up, I absolutely feel this amazing
    site needs a lot more attention. I’ll probably be returning to read through more, thanks for the information!

    Here is my homepage

    Reply
  6. Christen

    wonderful submit, very informative. I ponder why the opposite experts of this sector do not notice this.
    You must proceed your writing. I am confident,
    you have a huge readers’ base already!

    Reply
  7. rcwebclub.com

    I’m amazed, I have to admit. Seldom do I encounter a blog that’s both educative and amusing, and without
    a doubt, you’ve hit the nail on the head. The issue is something that not enough folks are speaking intelligently about.

    I’m very happy that I found this during my search for something regarding this.

    Reply
  8. black bo staff

    Along with the MMA rank, our students are co-promoted in Muay
    Thai and Brazilian Jiu-Jitsu as well. However, many martial arts schools make the
    mistake of instructing their students either late in their
    development or not at all. To me, these factors are more important than any other of the above factors and can make or break your martial arts experience.

    Feel free to surf to my web-site – black bo staff

    Reply
  9. oumma.com

    If you’re pounding away on it during your workout routine, or if kids are scrambling across the surface as they
    run around their jungle gym, you can be sure that you or
    the children will wear out long before the floor does. Lower yourself down to the point where you feel comfortable, then raise yourself
    back up to the starting position. 5 ounces, so you’ll surely want to pack it in your bag for the return trip.

    Reply
  10. desistreams.net

    Yesterday, while I was at work, my cousin stole my iPad and tested to see if it can survive a 30 foot drop, just so she can be
    a youtube sensation. My iPad is now destroyed and she has 83 views.

    I know this is totally off topic but I had to share it with
    someone!

    Reply
  11. 18x

    Generally I don’t read article on blogs, but I wish to
    say that this write-up very pressured me to check out and
    do it! Your writing style has been surprised me. Thanks, quite nice article.

    My blog post 18x

    Reply
  12. Aidan

    This entails plumbing work, fixing electrical fittings, and
    providing various accessories for maximum pleasure and comfort.
    When deciding upon a scale, you should make sure
    that the platform is big enough for your needs. Should I expect to see the
    measured copper content of my.

    Reply
  13. Scarlett

    Hey There. I found your blog using msn. This is a really well written article.
    I’ll be sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I will definitely comeback.

    Reply
  14. sword store

    So this technique requires a lot more practice and dedication. Modern police
    forces, security agencies, and concerned civilians continue to draw upon the
    techniques and experiences of the ancient masters. To me, these
    factors are more important than any other of the above factors and can make or break your martial arts experience.

    Feel free to surf to my weblog: sword store

    Reply

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>