How to use Facebook PHP SDK v.3.0.0 with Codeigniter?

Written by msnisha

Topics: Codeigniter

There is some changes has been done in the Facebook PHP SDK v.3.0.0. There is no more method named as getSession. So if you have updated to the new Fecebook PHP SDK then you might have to modify your Codeigniter Facebook connect library.

You can follow these simple steps to have a working Codeigniter Facebook library.

  1. Create a Config file in application/facebook.php with the following code in it.
  2. $config['appId'] = 'Your Facebook App ID';
    $config['secret'] = 'Your secret Code';
  3. There is two files provided starting from V.3.0.0 of Facebook PHP SDK. Create a folder in application library and name it as facebook.
  4. Download the Facebook PHP SDK files and place it in the folder application/library/facebook. You can download it from https://github.com/facebook/php-sdk
  5. Create a new file and name it as fb_connect.php in application/library and copy the following code inside that folder. 
    <?php
    	include(APPPATH.'libraries/facebook/facebook.php');
    
    	class Fb_connect extends Facebook{
    
    		//declare public variables
    		public 	$user 			= NULL;
    		public 	$user_id 		= FALSE;
    
    		public $fb 			= FALSE;
    		public $fbSession	= FALSE;
    		public $appkey		= 0;
    
    		//constructor method.
    		public function __construct()
    		{
                        $CI = & get_instance();
                        $CI->config->load("facebook",TRUE);
                        $config = $CI->config->item('facebook');
                        parent::__construct($config);
                        $this->user_id = $this->getUser(); // New code
    
                        $me = null;
                        if ($this->user_id) {
                            try {
                                $me = $this->api('/me');
                                $this->user = $me;
                                } catch (FacebookApiException $e) {
                                    error_log($e);
                                }
    			}
    		} 
    
    	} // end class
    

Now create a Controller and name it as user, and write the following methods in it.

  
	function loginByFacebook(){
        	$this->load->library('fb_connect');
	        $param['redirect_uri']=site_url("user/facebook");
	        redirect($this->fb_connect->getLoginUrl($param));
	}

	function facebook() {
	        $this->load->library('fb_connect');
	        if (!$this->fb_connect->user_id) {
	            //Handle not logged in,
	        } else {
	           $fb_uid = $this->fb_connect->user_id;
	           $fb_usr = $this->fb_connect->user;
	           //Hanlde user logged in, you can update your session with the available data
        	   //print_r($fb_usr) will help to see what is returned
	        }
	}

 

 

That is all about the coding now when ever you need to login with facebook just redirect to user/loginByFacebook and your login will handled automatically by Facebook. But you need to update the facebook() method with the actions success and failure conditions.

37 Comments For This Post I'd Love to Hear Yours!

  1. msnisha says:

    It worked for me. Please try all steps or send me ur code I can help in debug.

  2. Pavan says:

    It worked. Thank you

  3. Hi!

    I’ll give this a try.

    Perhaps you could provide a zip file with all the files you mention to create, so that we can just drag and drop into the application folder, think about it.

    Will come back after trying.

  4. Ben says:

    Got it working now, is there any way to post to a user’s wall?

  5. niksam says:

    can you provide full source code ?

    Codeigniter 2.0 with facebook sdk 3.0.1 ?

  6. msnisha says:

    Yes. Please download it from the post How to post on user’s wall on Facebook?

  7. David Rosendo says:

    Having a error showing up:
    Great Help your tutorial!

    Im getting the following error:
    Fatal error: Call to undefined function site_url() in /home/xpto/public_html/f6/application/controllers/user.php on line 33

    Any help?

    Is there a View File? for the views Folder?

    Also, how can I bypass the install app feature and instead show the Popup one…?

  8. msnisha says:

    I forget to mention that, you will have to load the url helper to get the function. I have done it in the auto-load config file. I think this is the preferred method is to redirect user to facebook login screen then it will work fine in all device.

    Any way if you need a popup please follow this to display the login button.
    <fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
    This will open the popup window. But please make sure facebook javascript loaded in the starting of the page.

  9. markus says:

    can you please provide the info in your email to me too?

  10. msnisha says:

    Please check your email.

  11. tiktak31 says:

    wow this is awsome… thnks very much..

  12. Duncan says:

    I’m having some trouble that’s got me pulling out my hair:

    On my local machine and on the testing machine which is on Godaddy it all works fine, but on production – which is also godaddy – the returned facebook user is always null:

    object(Fb_connect)#21 (13) {
    ["user"]=> int(0)
    ["user_id"]=> int(0)
    ["fbLoginURL"]=> string(197) “https://www.facebook.com/dialog/oauth?client_id=xxxx&redirect_uri=http%3A%2F%2Fwww.ultimatedreamteams.com%2Fbracketchallenge%2Fusers%2Fsave_fb_user&state=xxxx”
    ["fbLogoutURL"]=> string(0) “” ["fb"]=> bool(false)
    ["fbSession"]=> bool(false)
    ["appkey"]=> int(0)
    ["appId:protected"]=> string(15) “xxxx”
    ["apiSecret:protected"]=> string(32) “xxxx”
    ["signedRequest:protected"]=> NULL
    ["state:protected"]=> string(32) “xxxx”
    ["accessToken:protected"]=> string(48) “xxxx|xxxx”
    ["fileUploadSupport:protected"]=> bool(false)
    }

    There is some config difference on this server as I had to add a ‘?’ to my .htaccess rule (index.php?/ instead of index.php/) for CI to work. I’ve tried all sorts of config variations for uri_protocol but it the FB user is always 0.

    I just can’t figure out where the problem is. Any ideas? Or at least how I can trouble shoot?

    The production url is: http://www.ultimatedreamteams.com/bracketchallenge/home

  13. Duncan says:

    SOLVED:

    Add this to controller functions that use FB_connect:

    parse_str(substr(strrchr($_SERVER['REQUEST_URI'], “?”), 1), $_REQUEST);

    Whatever it is that requires the ‘?’ added to the .htacess rule messes up $_REQUEST. I had tried the above with $_GET which didn’t work as the FB api uses $_REQUEST

  14. Marko says:

    I followed your tutorial and after loginbyfacebook i got blank page, vever getting into facebook method.I noticed “?” in url thinking it may have caused problems, but i dont know the workaround. Please help

  15. I have an error message – below

    Fatal error: Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP extension.’ in C:xampplitehtdocshsdapplicationlibrariesfacebookbase_facebook.php:19 Stack trace: #0 C:xampplitehtdocshsdapplicationlibrariesfacebookfacebook.php(18): require_once() #1 C:xampplitehtdocshsdapplicationlibrariesfb_connect.php(2): include(‘C:xamppliteht…’) #2 C:xampplitehtdocshsdsystemcoreLoader.php(824): include_once(‘C:xamppliteht…’) #3 C:xampplitehtdocshsdsystemcoreLoader.php(100): CI_Loader->_ci_load_class(‘fb_connect’, NULL, NULL) #4 C:xampplitehtdocshsdapplicationcontrollersuser.php(55): CI_Loader->library(‘fb_connect’) #5 C:xampplitehtdocshsdapplicationcontrollersuser.php(10): User->loginByFacebook() #6 [internal function]: User->index() #7 C:xampplitehtdocshsdsystemcoreCodeIgniter.php(339): call_user_func_array(Array, Array) #8 C:xampplitehtdocshsdindex.php(201): require_once(‘C:xamppliteht…’) #9 {main} thrown in C:xampplitehtdocshsdapplicationlibrariesfacebookbase_facebook.php on line 19

  16. So far this script seems to be great, it does show me the information I expect to get.

    But one thing I wonder, where can I add more information which I would like to get from the user?

    For example:
    ‘scope’ => ‘publish_stream,user_birthday,user_location,user_about_me, user_photos’,

  17. Forget my last comment, I figured it out, was simple, hehe.

    But one other thing I wonder, is how do I run FQLs like this?

    try{
    $fql = “select name, birthday_date, sex, about_me, name, current_location, email, uid from user where uid=” . $user;
    $param = array(
    ‘method’ => ‘fql.query’,
    ‘query’ => $fql,
    ‘callback’ => ”
    );
    $fqlResult = $facebook->api($param);
    }

  18. Wondering Coder says:

    Sorry for asking this, I’m just starting to learn about mobile application.
    Just want to clarify about this:
    Create a Config file in application/facebook.php with the following code in it.
    Source code

    $config['appId'] = ‘Your Facebook App ID’;
    $config['secret'] = ‘Your secret Code’;

    do you mean I will create a facebook.php under the application folder? And in that php file those 2 lines of codes will be included?
    e.g
    <?php
    $config['appId'] = 'Your Facebook App ID';
    $config['secret'] = 'Your secret Code';

    please reply. thanks you in advance

  19. Jason says:

    Hi,

    My application has a problem. I can’t get the user data. Could you please help me to take a look?

    controller action:
    function test()
    {
    $data['title'] = ‘Facebook API Testing’;

    $data['user_id'] = $this->fb_connect->user_id;
    if($data['user_id'])
    {
    $data['user_profile'] = $this->fb_connect->user;
    }
    if($data['user_id'])
    {
    $data['logout_url'] = $this->fb_connect->getLogoutUrl();;
    }
    else
    {
    $data['login_url'] = $this->fb_connect->getLoginUrl();
    }

    $this->template->load(‘template’, ‘facebook_connect/test’, $data);
    }

    view file:
    php-sdk

    <a href="”>Logout

    Login using OAuth 2.0 handled by the PHP SDK:
    <a href="”>Login with Facebook

    PHP Session

    Your Avata
    <img src="https://graph.facebook.com//picture“>

    Your User Object (/me)

    You are not Connected.

    Thanks.

  20. Josh says:

    This looks great! Thanks for the tips, but when I go to user/facebook it takes me to a facebook page that says an error occured, try again later. The info in the url looks like it has the correct redirect_uri any ideas what I’m doing wrong? Thanks!

  21. msnisha says:

    Have you changed the configuration details to match with your URL and api key?

  22. stuman says:

    Thanks for the tutorial!
    But how can i access user’s friends data (i.e friends’ names) ?

    thanks

  23. Johnson says:

    Hi, nice tutorial. Works well for me.

    But how do I get the access token when a user logs in?

  24. Emrah says:

    its working. thank you for this tutorial.
    my ci ver: 2.1.2

  25. sp says:

    A PHP Error was encountered

    Severity: Warning

    Message: include(application/libraries/facebook/facebook.php) [function.include]: failed to open stream: No such file or directory

    Filename: libraries/fb_connect.php

    Line Number: 2

Leave a Comment Here's Your Chance to Be Heard!