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

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

  1. Keesha

    Thanks a bunch for sharing this with all of us you
    actually realize what you are talking about! Bookmarked.

    Please also seek advice from my website =). We can have
    a link exchange agreement between us

    Reply
  2. maths tricks for bank exams

    Hello! This is my 1st comment here so I just wanted to
    give a quick shout out and say I really enjoy reading through your blog posts.
    Can you recommend any other blogs/websites/forums that cover
    the same subjects? Thanks a lot!

    Reply
  3. Earlene

    If you’re hanging pictures that aren’t a “set” and are different
    dimensions, then here are some further tips:.

    Other digital scales offer functions like measuring body fat and
    body water percentages for a more complete picture of the health.
    I also enlightened her on the differences between digital and analog scales.

    Reply
  4. Dwight

    Attractive element of content. I simply stumbled upon your web
    site and in accession capital to claim that I get actually enjoyed account your weblog posts.
    Any way I’ll be subscribing in your feeds or even I success you get right of entry to consistently quickly.

    Reply
  5. Ned

    After pregnancy, women tend to weigh an average of 4.
    The problem is, more often than not, most people have read about, searched and even pondered on what they think
    or believe happiness is… It appears that many of us have pretty much accepted to some extent “
    What happiness is. Should I expect to see the measured copper content of my.

    Reply
  6. Leandro

    IR night vision The door bell phone support IR night vision. Find free
    printable pumpkin carving stencils and patterns online for Halloween 2010 here.
    The expense of the wifi doorbell furthermore is dependent upon the particular certain characteristic with
    all the wi-fi doorbell since it really is different coming from 1 entrance bell about the distinct additional.

    Reply
  7. Francisca

    This particular kind of doorway bell be placed by you everywhere
    of your house however whilst putting this kind of kind
    of front door bell something that you should take into consideration is basically that you
    just need to put the wifi doorbell because spot to enable
    you to definitely just hear the sound of your bell. 35K resistor across these pin-outs shunts
    the IC to the above gain. In fact, the only thing i – Books lacks
    is a big library of titles, which will come in time.

    Reply
  8. weight scales

    The proposed weight loss is in the range of half a
    pound to a pound (. These bed scales allow recording the weights of the patient
    with least effort and discomfort. “Insist on quality, brand strategy is the first international background of economic globalization the only way for Chinese enterprises.

    Reply
  9. home business

    Most people who go into business do so because they’re somewhat of an expert in their
    niche. Hence, it is very important to design the digital marketing concept keeping in mind these varied age groups of customers.
    You can compare the courses and training offered by these institutes and also read testimonials from previous participates who have taken training.

    Reply
  10. www.youchoose.net

    A Westinghouse module that features five channels can be
    found for under $60 and includes one intercom unit.
    Find free printable pumpkin carving stencils and patterns online for Halloween 2010 here.

    Remember to keep a record of the business and the number for future reference.

    Reply
  11. kocioł gazowy

    Aw, this was a very good post. Finding the time and actual effort
    to produce a good article… but what can I say… I put things off a whole lot and don’t manage to get nearly anything done.

    Reply
  12. Francine

    A typical bathroom weight scale may deliver inaccurate
    guidance given that an individual can be slightly obese and
    nonetheless regarded as in good health. But just as one day, as we
    suddenly realize that we weigh pounds more than we want to, we may realize
    that a stumble or uneven pavement causes a fall that we would have avoided in the past.
    Note that doing the daily cleaning routine cleaning work to prevent
    the production of dirt and found that dirt should be removed in time, do
    not let it form a old scale and thick dirt.

    Reply
  13. Jeremy

    The use of additional transmitters can be some of the best things
    to use when it comes to getting wireless pet barrier systems to work as well
    as possible. Door – Bot is an interesting concept from BOT Home Automation.
    In addition, you get a Walkie Talkie that can be used for effective supervision of the house
    or business property.

    Reply
  14. bathroom scale

    A typical bathroom weight scale may deliver inaccurate guidance
    given that an individual can be slightly obese and
    nonetheless regarded as in good health. These scales are far
    more accurate and they look elegant and modern in contrast to the normal weighing scale, which you discover that are available in the market.
    Folks of all ages are finally realizing that in order for them to take the next step
    forward in having a good life requires their taking
    responsibility for how they feel.

    Reply
  15. eat smart scale

    There are multiple pressure sensors within the board so it is capable of
    determining your center of balance and can detect what direction you are
    leaning in and how hard. Lower yourself down to the point where you feel comfortable,
    then raise yourself back up to the starting position. In the least expensive class you have canvases of high concentration polymers.

    Reply
  16. prodaja mobilnih telefona

    Each conversation ended with the words: “We need to meet soon,” and
    I somehow felt that behind this “I” is probably not hiding any “want”, because when you
    get off the bus, I will not have to fill a severe void,
    and even if it comes up again, you can call it yet, instead opt for
    a meeting. Samsung Jet has Snappy performance, it
    also owns good keypad, Wi-Fi, 3. depending upon the features and
    requirements of consumers.

    Reply
  17. ugradnja staklenih prizmi

    Do you lack the privacy you wish, are you concerned about the safety of the family or workers, or simply looking
    for a hot check out add style in your property. After bending,
    grinding edge, state in detail such as processing of engraved
    glass, 7003-7005;. A brightly coloured wall will fit in aptly in a kids’ room.

    Reply
  18. buy from china online

    Nice publish. There exists a ton you can buy by means of TAOBAO.
    Through minor household products, as a way to in addition to matter you could find
    can be had generally there and truly normally cheaper.

    Reply
  19. Yolanda

    A unique code prevents nearby intercom systems from accessing the system.
    Wireless alarm systems keep off the thieves and burglaries, making your home more secure when you are out.
    Pick a wireless doorbell here at great price & you can be assured of great quality too.

    Reply
  20. doorbell

    A unique code prevents nearby intercom systems from accessing the
    system. This USB kit is good for people who need
    to monitor what’s going on in their office at home or at work.

    Seal the gaps with the help of a trim molding and you are now ready to
    enjoy the benefits of your system.

    Reply
  21. Hamish

    Some examples are swimming, going to the park, taking a walk, and taking a pottery class.

    Door – Bot is an interesting concept from BOT Home Automation. All the products on the site come with a manufacturer’s warranty and a 30 day money back
    offer, so if you do not like the doorbell that you
    buy, you can simply return it and get your money back, no questions asked.

    Reply
  22. Taj

    For plug-ins, as the name suggests, the bell receiver is plugged into a wall socket.
    The runner has on a white t-shirt and dungaree pants. A mesh pocket on the exterior of the bed
    accommodates a tee shirt or shorts and provides optimal air circulation that allows the dog to easily detect the owner’s calming,
    familiar scent.

    Reply
  23. Martha

    In your area, the temperatures may not be as low as to make the lily bulb “go to sleep” naturally and vernalize,
    cooling period which prompts the lily plant to bloom again. After you’ve
    just completed a strenuous workout – unless you’re measuring pre and post-workout hydration levels.

    I made an effort to crank out 100 kettle bell swings split
    up, but generally settled with 80.

    Reply
  24. Thao

    Some examples are swimming, going to the park, taking a walk,
    and taking a pottery class. This USB kit is good for people who need
    to monitor what’s going on in their office at home or at work.

    After setting up this type of system, each door will have its own transmitter, resulting in a different ringtone.

    Reply
  25. beritapilihan.web.id

    For example, playing video files (divx, xvid etc) only consumes about 25-30% of the CPU.
    The power and volume buttons are solid and the edging feels comfortable when handling the tablet for a long period of time.
    Of late, there are some fresh characteristics which have
    been inculcated in the gaming laptops, like the three external displays equipped ATI’s Eyefinity.

    Reply
  26. iznajmljivanje apartmana beograd

    The key to living comfortably in a tigh spaced apartment is to get creative with the space.
    Its history dates back to 11th century, when Sviatopolk II Iziaslavych,
    supreme ruler of the Kievan Rus from 1093 to 1113, founded the monastery.
    During that century, this church was an ingenious architecture as
    it can easily be dismantled once invaders like the Turks are in the area
    and rebuilt in another safer location.

    Reply
  27. Tangela

    It means the video telephone can only unlock under the surveillant condition of monitor, which can avoid the accident circumstance
    without monitoring, such as misoperation or
    children random press on the unlock key cause the door open etc.
    The next room is an area where Rapunzel paints
    all her murals. There are also so many models you can choose between, there will unquestionably be a doorbell out
    there suitable for you.

    Reply
  28. Camille

    You might even look forward to those door-to-door solicitors
    with the Swann MP3 DJ Doorbell ($49. The next room is an area where Rapunzel paints all her murals.
    Here is a list of some of its advantages and disadvantages:.

    Reply
  29. bathroom scale

    A typical bathroom weight scale may deliver inaccurate
    guidance given that an individual can be slightly obese and nonetheless regarded as in good health.
    Other digital scales offer functions like measuring body
    fat and body water percentages for a more complete picture of the health.

    I also enlightened her on the differences between digital and analog scales.

    Reply
  30. website design

    ” (if you know a bit about yoga yourself) or “I’ve never tried yoga, would you recommend
    it. Patient suffering from this disorder is recommended nutritional intake of the diet play with vegetables rich and
    full of your company. The only issue I found with the Minawear line was the lack of different sizes.

    Reply
  31. Dianna

    There are multiple pressure sensors within the board
    so it is capable of determining your center of balance and can detect what direction you are
    leaning in and how hard. There are some kinds of this software that will cost the business more money than it will earn back.
    Tanita bathroom scales are extremely good in achieving the following purpose.

    Reply
  32. videncia economico

    Aw, this was aan extremely nice post. Finding the tie aand actual effort to make a very good article… but
    what can I say… I procrastinate a lot and never manage to gget nearly anyhthing done.

    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>