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

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

  1. bathroom scale

    This feature definitely comes in handy especially if
    you are trying to trim down your weight. 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.
    A birthday card that arrives on time or early says “I cared enough” much more than a belated card.

    Reply
  2. wireless doorbells

    Delco will testify as the lawyer’s forensic expert for Finley.
    Door – Bot is an interesting concept from BOT Home Automation.
    Seal the gaps with the help of a trim molding and you are now ready to enjoy the benefits of your system.

    Reply
  3. Kim

    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. Supreme Commander can be a very, very
    good game – but only under controlled circumstances. A birthday card that arrives on time or
    early says “I cared enough” much more than a belated card.

    Reply
  4. Keesha

    Delco will testify as the lawyer’s forensic expert
    for Finley. One of the advantages of wireless doorbells is that the end unit with the bell or chimes
    unit can be left mobile and taken from room to room, even into the garden; such is the ease of mobility, without being tied down literally to a set of cables and wires.
    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
  5. Camilla

    The prospective Internet marketer now has to choose from an abundance of sites that present
    questionable guarantees at best. Although social media marketing has become extremely popular in today’s day and age, there are
    still many businesses that haven’t figured out how to do it right.
    Basically PLR stands for Private Label Rights and it is
    pre-written or pre-made content that you can use to promote your business in many different ways.

    Reply
  6. Gear Peers

    The security companies therefore must ensure the most appropriate and durable equipment, installations, and maintenance programs to ensure a safe and secure existence within our society.
    The foremost piece of equipment available to the hunter for year round scouting is
    a wildgame camera. I’m also starting to discover and enjoy playing with the i – Phone camera a lot
    more because of that.

    Reply
  7. sign up for uber

    Colorful, well-read and dressed, entertaining and informative,
    George offers his fares much more than most drivers. You
    should realize that the more you drive your car
    the more damage is caused to your car tires but if you do
    not use your car too much and keep it parked even then the rubber of the
    tires starts getting damaged. With like-minded entrepreneurs who strive
    for their own personal success, All – State maintains a higher level of reliability and safety unmatched by their competitors.

    Reply
  8. Dennis

    Your style is really unique compared to other folks I have read stuff from.

    Thanks for posting when you’ve got the opportunity, Guess I will just book mark this site.

    Reply
  9. Alissa

    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.
    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
  10. wireless doorbell

    Delco will testify as the lawyer’s forensic
    expert for Finley. The power unit will simply plug into a
    standard wall socket and no further installation will be needed.
    Make sure your kids know the rules about what to
    do when the doorbell rings.

    Reply
  11. Willian

    A unique code prevents nearby intercom systems from accessing the system.

    The next room is an area where Rapunzel paints all her murals.

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

    Reply
  12. renting apartments in belgrade

    However, despite of the falling mortgage rates, many are still unable to purchase a home.
    A medium-class condo with Wi-Fi, 1 washroom and a spacious kitchen, measuring 1250 square feet goes for an average price of $1500 month.
    Check out if the rental can satisfy all that you want.

    Reply
  13. mow.so

    You might even look forward to those door-to-door solicitors with the Swann MP3 DJ Doorbell ($49.

    It’s easy to tell some apps were rushed out the door in order to arrive on day one.
    After setting up this type of system, each door will have its own transmitter, resulting in a
    different ringtone.

    Reply
  14. Ava

    You have nothing to worry about your own confused strategies for fat loss and you’re fully protected under competent trainers.
    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
  15. Tangela

    If some one desires to be updated with most up-to-date technologies afterward
    he must be pay a quick visit this web site and be up to date everyday.

    Reply
  16. June

    A typical bathroom weight scale may deliver inaccurate guidance given that
    an individual can be slightly obese and nonetheless regarded as
    in good health. This will help eliminate the unconscious snacking that is so much a
    part of being overweight. A birthday card that arrives on time or early says
    “I cared enough” much more than a belated card.

    Reply
  17. workout time

    You have nothing to worry about your own confused strategies for fat loss and you’re
    fully protected under competent trainers. Typically you need to actually know what you are doing in order to get an accurate and reliable measurement.
    One weekend she did us the “favor” of throwing out a potted Amaryllis bulb; I rescued it just in time from the rubbish, but not before we argued as to whether there was
    anything actually growing in that pot of bone dry dirt under the pantry cabinets.

    Reply
  18. Alfonso

    You have nothing to worry about your own confused strategies for fat
    loss and you’re fully protected under competent trainers.

    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
  19. Jeanett

    Products are generally shipped within one working day of
    placing the order and receiving the payment. This is a great alternative to the
    traditional door bell set up, as installation of multiple pushbuttons for multiple doors can be
    coordinated with multiple receivers for larger houses or buildings that may call for
    many receivers. Remember to keep a record of the business
    and the number for future reference.

    Reply
  20. brochure design

    I don’t know whether it’s just me or if perhaps
    everyone else encountering issues with your blog. It appears like some of the text in your content
    are running off the screen. Can someone else please provide feedback and let me know if
    this is happening to them too? This might be a problem with my internet browser because I’ve had this happen before.
    Many thanks

    Reply
  21. golfing on the coast

    I was very happy to find this web site. I want to to thank you for ones
    time for this wonderful read!! I definitely liked every bit of it and
    I have you book marked to see new information in your site.

    Reply
  22. transplatacija kose

    This is done very carefully in order to ensure a good result.
    Hair transplantation is a team effort, and each member of our
    surgical team is highly trained to achieve the desired result.
    Hair grafts are exactly hair follicles that are removed from the
    back of the head to the front.

    Reply
  23. zastitne folije za mobilne telefone

    The 3G standards have been classified into
    three parts – W-CDMA which means ‘Wideband – Code Division Multiple Access’.
    You will be able to utilize your cell phone the same way you would have done
    minus the case; calls can still be made and voice
    quality will not be affected. In order to maintain the
    expensive and extravagant look of this phone consider using a protective cover.

    Reply
  24. armodafinil cost

    You need a health insurance plan if you are unwell or injured and you
    require it to work for you and you need it to work fast and efficiently.
    Regardless of the goals you have set in mind, there are many great benefits to following a healthy
    diet menu. It helps women in attaining good health by reducing the level of nervous disorders like anxiety,
    stress and depression.

    Reply
  25. Discover More Here

    The Food and Drug Administration stops short of calling them healthier than traditional cigarettes
    and is admonishing advertisers from making that claim on their web sites.
    They offer 5 different flavors including vanilla, apple and strawberry
    and a variety pack. Once you know how you can thoroughly search the net,
    you can get these coupon codes.

    Reply
  26. our website

    Even while the sale is on, the health groups without any proven cause still fear that these unregulated, cigarette-shaped devices maintain users’ links with smoking and
    could cause nicotine poisoning. The analysis of liquids was done using nuclear magnetic resonance
    (NMR) spectroscopy to accurately measure the formaldehyde content of
    the vapor generated when standardized ‘puffs’ were collected and analyzed.
    There are no ashes or tons of butts to clean out constantly.

    Reply
  27. Full Article

    In comparison to regular super minis where small cartridge size barely provides 4-5 cigarettes worth of smoking; the Super Mini, can go upto the equivalent of 10 cigarettes without having to replace
    the cartridge. The E-cigs also deliver atomized particles of
    propylene glycol or glycerin propellants, and low concentrations of carbonyl compounds
    as propellant byproducts. Before you start using
    Green Smoke, review the directions first and understand how it works first.

    Reply
  28. Full Article

    These are designed in such a way that it produces vapor instead
    of smoke. Use the republication of the article as a means of re-submitting as
    your own work- any notification of this will result in the removal of the duplicate content.
    With every cigarette we smoke, we inhale all those 4000 chemicals in our body,
    out of which some are poisonous and severe in nature; most of
    these chemical are found in dry-cleaning supplies.

    Reply
  29. Look At This

    The Food and Drug Administration stops short of calling them healthier than traditional cigarettes and is admonishing advertisers
    from making that claim on their web sites. Also, my lungs are not being coated with the horrible chemicals and thick black tar
    that they were when I was smoking up to a pack of cigarettes on a daily basis.
    Long term smoking of traditional cigarettes often leaves the user suffering from halitosis
    (bad breath) as well as badly discolored teeth.

    Reply
  30. Get More Info

    The use of electronic cigarettes truly copies the act of inhaling and also exhaling smoke from a actual cigarette.

    No more clouds of noxious fumes following me around, and attaching to
    my clothes and hair. Certain categories have accumulated much knowledge enabling planning and launching of
    hits with a practical probability of success.

    Reply
  31. Check This Out

    Manufacturers admit that it is not designed to stop smoking.

    No more clouds of noxious fumes following me around, and attaching to my clothes and
    hair. Before you start using Green Smoke, review the directions
    first and understand how it works first.

    Reply
  32. Home Page

    Generally, the cartridge is flavored; it also is the deciding factor to the strength of your smokeless electronic cigarettes.
    Take the syringe then suck the E- Juice from it container and release it into the tiny filler in the cartridge and
    allow it to flow in to an acceptable level.
    Long term smoking of traditional cigarettes often leaves
    the user suffering from halitosis (bad breath) as well as badly discolored teeth.

    Reply
  33. Get More Information

    Just a hard chair, a plastic bucket and a bed with no mattress.

    No more clouds of noxious fumes following me
    around, and attaching to my clothes and hair.
    The patented Electronic Cigarette offers to effectively simulate the
    experience of smoking an actual cigarette, without any of the health or legal issues surrounding traditional cigarettes.

    Reply
  34. Recommended Reading

    In an e cigarette kit, the most important component
    is the electronic cigarette and e-juice, which one will find in nearly any e cigarette kit.
    Since there are many companies to choose from, you will
    find it difficult to select the most reliable and
    reasonable company from the bunch. Another unique aspect of electronic cigarettes is the fact that the cartridges need to be regularly replaced given that the liquid in them is vaporized although the cigarette
    is becoming smoked.

    Reply
  35. Read More Here

    The device contains cartridges that contain small amounts of nicotine in a liquid form.
    As a result, it becomes difficult to trace non-compliant firms out who evade taxes.
    As a result, many smokers have begun to buy e-cigarettes as an alternative to
    traditional tobacco products.

    Reply
  36. Discover More Here

    When you have a particular brand of electronic cigarette in mind, then it will be best to use
    specific search phrase or keyword if you enter it on search engines.
    Certain groups may have the public’s best interests in mind and just want more clinical
    studies to be done. There are no ashes or tons of butts to clean out constantly.

    Reply
  37. Visit This Link

    Among others, the approach to pulling tobacco growers and labor force out of tobacco industry and putting them in agro-based
    industry appears very appealing in economic and social sense.
    Another doctor, who also quit smoking after only 6 weeks of using an electronic cigarette,
    has validated that it only takes an average of 12 puffs from an e cigarette to give the same quantity of nicotine that a traditional cigarette does.
    The patented Electronic Cigarette offers to effectively simulate
    the experience of smoking an actual cigarette,
    without any of the health or legal issues surrounding traditional
    cigarettes.

    Reply
  38. Click This Link

    When you have a particular brand of electronic cigarette in mind, then it will be
    best to use specific search phrase or keyword if you enter it on search engines.

    No more clouds of noxious fumes following me around, and
    attaching to my clothes and hair. Long term smoking of
    traditional cigarettes often leaves the user suffering from halitosis (bad
    breath) as well as badly discolored teeth.

    Reply
  39. Read Full Report

    The list of brands covered by a website is extensive. Take
    the syringe then suck the E- Juice from it container and release it
    into the tiny filler in the cartridge and allow it to flow in to an acceptable level.
    With every cigarette we smoke, we inhale all those 4000
    chemicals in our body, out of which some are poisonous and severe in nature; most of these chemical are found in dry-cleaning supplies.

    Reply
  40. Discover More Here

    The Food and Drug Administration stops short of calling them healthier than traditional cigarettes and is
    admonishing advertisers from making that claim on their
    web sites. The analysis of liquids was done using nuclear magnetic resonance (NMR) spectroscopy to accurately measure the formaldehyde content of the vapor generated when standardized ‘puffs’ were collected and analyzed.
    With every cigarette we smoke, we inhale all those 4000
    chemicals in our body, out of which some are poisonous and severe in nature; most of
    these chemical are found in dry-cleaning supplies.

    Reply
  41. Read Full Report

    The Food and Drug Administration stops short of calling them healthier than traditional cigarettes and is admonishing advertisers
    from making that claim on their web sites. It is to be operated in the event of a fire
    and it will shut down all blowers, fuel transfer pumps,
    purifiers, incinerators, and boilers. As a result, many smokers have
    begun to buy e-cigarettes as an alternative to traditional tobacco products.

    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>