Facebook PHP SDK and CodeIgniter for basic user authentication

Posted by Danny Herran on Feb 24, 2011 in Backend | 209 comments


With CodeIgniter 2, plugins are no longer an option. Usually you would just add the Facebook PHP SDK as a plugin and you were good to go, but now, you need to make a little modification to the SDK in order to use Facebook Connect on your CodeIgniter application. Lets start by explaining what is, how to get started and how to authenticate an user using the Facebook API.

In this post I will only cover the user authentication process using the Facebook PHP SDK. However, you can do almost anything with the API, just take a look at the official documentation if you have any doubts:

https://developers.facebook.com/docs/graph-api/using-graph-api/

All the methods related to the user object (very useful): https://developers.facebook.com/docs/graph-api/reference/user/

First of all, a couple of links so you can download the necessary files:
CodeIgniter: http://www.codeigniter.com
Facebook PHP SDK: https://github.com/facebook/facebook-php-sdk (download the 3 files inside the /src/ folder).

Once you have your CodeIgniter set up, you can proceed to modify the Facebook PHP SDK and make it a library. What you need to do is the following:

  1. Autoload the CodeIgniter Session Library from application/config/autoload.php
  2. Facebook will try to pass the signed request via GET to your application. So, please make sure your CodeIgniter installation is set to allow the GET array. To do this, find the $config[‘allow_get_array’] in your application/config.php file and set it to TRUE.
  3. Once you download the FB PHP SDK, go to the “src” folder of the downloaded package and copy the “facebook.php”, “base_facebook.php” and “fb_ca_chain_bundle.crt” files to your CI application/libraries folder.
  4. Rename the file “facebook.php” to “Facebook.php” (notice the F in capital) present in your application/libraries folder.
  5. Add the following line to the beginning of the “Facebook.php” file:
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    

The next step is to build a model that will handle the authentication process. It basically requests the session data and saves it into a CI session var. The view and the controller can take care of the rest.

class Facebook_model extends CI_Model {
	public function __construct()
 	{
 		parent::__construct();
 		$config = array(
 						'appId'  =--> 'XXXXXXXXXXXXXXXXXXX',
						'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX',
						'fileUpload' => true, // Indicates if the CURL based @ syntax for file uploads is enabled.
						);

		$this->load->library('Facebook', $config);

		$user = $this->facebook->getUser();

		// We may or may not have this data based on whether the user is logged in.
		//
		// If we have a $user id here, it means we know the user is logged into
		// Facebook, but we don't know if the access token is valid. An access
		// token is invalid if the user logged out of Facebook.
		$profile = null;
		if($user)
		{
			try {
			    // Proceed knowing you have a logged in user who's authenticated.
				$profile = $this->facebook->api('/me?fields=id,name,link,email');
			} catch (FacebookApiException $e) {
				error_log($e);
			    $user = null;
			}
		}

		$fb_data = array(
						'me' => $profile,
						'uid' => $user,
						'loginUrl' => $this->facebook->getLoginUrl(
							array(
								'scope' => 'email,user_birthday,publish_stream', // app permissions
								'redirect_uri' => '' // URL where you want to redirect your users after a successful login
							)
						),
						'logoutUrl' => $this->facebook->getLogoutUrl(),
					);

		$this->session->set_userdata('fb_data', $fb_data);
	}
}

Now the controller(s). Here, you just have to load the Facebook model and validate the session vars accordingly:

class Home extends CI_Controller {

	function __construct()
	{
		parent::__construct();

		$this->load->model('Facebook_model');
	}

	function index()
	{
		$fb_data = $this->session->userdata('fb_data'); // This array contains all the user FB information

		if((!$fb_data['uid']) or (!$fb_data['me']))
		{
			// If this is a protected section that needs user authentication
			// you can redirect the user somewhere else
			// or take any other action you need
			redirect('login');
		}
		else
		{
			$data = array(
					'fb_data' => $fb_data,
					);

			$this->load->view('home', $data);
		}
	}
}

For the view we will use the native FB SDK login/logout URLs which are supported by default:

  <?php if(!$fb_data['me']): ?>
  Please login with your FB account: <a href="<?php echo $fb_data['loginUrl']; ?>">login</a>
  <!-- Or you can use XFBML -->
<div class="fb-login-button" data-show-faces="false" data-width="100" data-max-rows="1" data-scope="email,user_birthday,publish_stream"></div>
  <?php else: ?>
  <img class="pic" alt="" src="https://graph.facebook.com/<?php echo $fb_data['uid']; ?>/picture" />

Hi <?php echo $fb_data['me']['name']; ?>,

    <a href="<?php echo site_url('topsecret'); ?>">You can access the top secret page</a> or <a href="<?php echo $fb_data['logoutUrl']; ?>">logout</a>

  <?php endif; ?>

This is a rough example of basic Facebook user authentication for your site. You can do a lot more and once you get a hang of it, it becomes pretty easy to work with. If there’s any doubts or questions, don’t hesitate to fill the comments section below, I’ll be happy to help.

Download the sample code.

Update Nov 19th, 2013: refreshed links and verified it is still working with the latest SDK and CodeIgniter..

Update Mar 1st, 2012: information on the new SDK. Also added a small update for custom permissions on the login URL. Requested by Alexintosh.

Update June 13th, 2011: Updated for the Facebook PHP SDK 3.0 +

Update May 3rd, 2011: Some servers seem to fail on cURL SSL certificates. To fix it, open the base_facebook.php file and find “CURLOPT_USERAGENT” (around line 132). Below that line add this:

CURLOPT_SSL_VERIFYPEER => false,
  • zechdc

    Do you know where I could find some Facebook PHP SDK documentation. It doesn’t seem to exist on facebook’s developers site.

  • Tell me about it. Starting with PHP and the Facebook SDK could be a bit rough because of the lack of official documentation, plus they always seem to be updating it and phasing out things. But if you use the CodeIgniter library and this particular link, I’m sure you will find pretty much everything:

    http://developers.facebook.com/docs/reference/api/

    Hope it helps!

  • Gabriel

    Hello Danny! Thanks for sharing that code, I’ve been trying to find something useful to help me with my first attempt to use Facebook login on a website I’m working on, and I think this is it!

    I followed your instruction but there’s one thing that doesn’t seem to work for me so if you can give me your input, it would be very helpful.

    In Facebook_model, the $uid variable contains the user id, this is perfect, but the $me variable is empty. I don’t get any PHP error. The only error I see, is a JavaScript error that says “e.root is undefined” in the Facebook all.js file, but I don’t think it’s related.

    Any idea what might be the problem? Thanks again for posting your code and for your input!

    • Gabriel, I’d try disallowing the permissions to the application on your Facebook profile and requesting them again through your application. The $me array contains the information requested to the user. If the user didn’t allow the app to pull information from their profile, the $me array will be empty.

      Try a print_r($me) after the line 23 of the model and check what’s returning.

      I would also recommend manually checking on your code if the information you need from the user is actually being pulled correctly from the user profile. I made a project a couple of months ago, where I was requesting the user’s email. For some reason, the SDK wasn’t able to pull it from a few users, and I had to modify my controller so it could manually request it if $me[’email’] was empty.

    • Gabriel

      Danny, I found part of the problem. It has nothing to do with your code (or mine). It’s the cURL request that the Facebook class does to get the info. It’s over SSL but it causes an error because the CA is not recognize as safe… I change the CURLOPT_SSL_VERIFYPEER option to false… It’s a breach in security, but until I find out how to fix it otherwise, it’ll have to do.

      Thanks!

  • Gabriel, actually I am having the exact same problem with a cURL request over SSL on nuSOAP right now. For some weird reason my cURL doesn’t want to work with SSL URLs on the production server. I guess we will have to recompile it.

    I am glad you found a workaround for the SDK though! Have fun.

  • neo

    hi,

    i want to read information from “recent activity” in my profil-feed.
    how can i do this via php-sdk ?
    i tried /me/feed but this is not what i want.
    I also put this question in facebook-forum without any answers. And the documentation was not helpful in this point 🙁

    thankxx

    neo

    • “me/feed” is what you want if publishing your most recent activity is your goal. If you want to post whatever your friends are doing, you need to use “me/home”. With both methods you can do a print_r() to have a preliminary view of the object returned by the SDK.

      http://developers.facebook.com/docs/reference/api/user/

      There is a “me/statuses” as well. Check the link above for information on each method. Really helpful!

      PD: I am adding that link to the main post for future reference.

  • neo

    hi Danny,

    thankx for your comment.

  • Colin Devroe

    Hi Dan, Is there anything different that needs to be done if I’m using CodeIgniter Reactor?

    • Hello Colin. Actually no. “CI Reactor” is the name given to the open source version of CI above 2.0. This code was tested on CI Reactor 2.0 and CI Reactor 2.0.2 so it should work no problem for you. Have fun!

  • PilotInspektor

    Hi Dan,

    Many thanks for this. However, I am getting an error message implementing your code:

    Message: Undefined property: Home::$session
    Filename: core/Model.php
    Line Number: 50

    Fatal error: Call to a member function set_userdata() on a non-object in ../application/models/facebook_model.php on line 48

    Any idea what the problem might be?

    • Remember to preload your session class. If the error persists please post the line of code that is throwing the error in your model.

  • ravinesh

    Thanks for code

  • Robert

    Thanks a lot!
    I’ve got a problem implementing the code however. My FB js (FB.init…. , FB.Event.s….. etc.) is exactly like your code and the PHP too. But when I log in using the FB button, the browser window keeps refreshing. The same thing when click Logout.
    I’m using it as an iframe app on Facebook.

    I’d appreciate any input! 🙂

    Thanks,
    Robert

    • Hi Robert. I’ve never tried it as an iframe app on Facebook. It could be any number of things. If you have a URL to test, it’ll be great.

  • Robert

    Hi Danny
    I’m just running it locally right, so I can’t really show you a live version :-/

    I’ve stripped the code and html into a Gist here https://gist.github.com/981119.
    If it’s to much I understand, and i don’t expect to to go through it.

    When I run the code/access the app before authorizing with my account, the page keeps refreshing.

    Robert

  • Robert

    Alright, here’s what I’ve come up with. https://gist.github.com/994891
    Seems to work.

  • Alan

    Hi Danny,

    I need your help. I got this following error while loading the facebook controller:

    Undefined property: Facebook::$facebook_model
    Filename: controllers/facebook.php

    It seems the error comes from this line in facebook_model.php:

    $this->load->library(“Facebook”, $config);

    Thanks!

    Alan.

    • Make sure the library is present in the “libraries” folder. The error comes from the controller. Please post the line throwing the error so I can take a look.

  • SangPetualang

    same problem as above ..

    Message: Undefined property: Home::$session
    Filename: core/Model.php
    Line Number: 50

    problem come from this line in model:

    $this->load->library(‘facebook’, $config);

    why you use $this before assigned as get_instance() to get the controllers?

    • This error is due to an non-initialized session library. You need to autoload the session library from config/autoload.php or manually load it in your controller.

      $this->load->library(‘session’);

  • SangPetualang

    when i print $this on the model .. it has no value ..
    so why you use method $this->load? that method from controller?

    no i got new problem on library class..

    the first method from facebook library is “getSession()”

    public function getSession() {
    if (!$this->sessionLoaded) {
    $session = null;
    $write_cookie = true;

    // try loading session from signed_request in $_REQUEST
    $signedRequest = $this->getSignedRequest();
    if ($signedRequest) {
    // sig is good, use the signedRequest
    $session = $this->createSessionFromSignedRequest($signedRequest);
    }

    // try loading session from $_REQUEST
    if (!$session && isset($_REQUEST[‘session’])) {
    $session = json_decode(
    get_magic_quotes_gpc()
    ? stripslashes($_REQUEST[‘session’])
    : $_REQUEST[‘session’],
    true
    );
    $session = $this->validateSessionObject($session);
    }

    // try loading session from cookie if necessary
    if (!$session && $this->useCookieSupport()) {
    $cookieName = $this->getSessionCookieName();
    if (isset($_COOKIE[$cookieName])) {
    $session = array();
    parse_str(trim(
    get_magic_quotes_gpc()
    ? stripslashes($_COOKIE[$cookieName])
    : $_COOKIE[$cookieName],
    ‘”‘
    ), $session);
    $session = $this->validateSessionObject($session);
    // write only if we need to delete a invalid session cookie
    $write_cookie = empty($session);
    }
    }

    $this->setSession($session, $write_cookie);
    }

    return $this->session;
    }

    the class always check $_REQUEST or $_COOKIE.. but we never set it before ..
    then the return always empty value ..

    so i still failed ..

    FYI .. for my problem above,
    i change to this :

    $this->CI =& get_instance();
    $this->CI->load->library(‘facebook’, $config);

    and i declare $CI first

    • Hello. There is no need to redeclare CI unless you’re working inside a helper or a library. In this case, we are loading the FB library directly with $this->load->library() inside the controller. And yes, you can use $this->load->library() directly from your controller. Take a look here: http://codeigniter.com/user_guide/general/creating_libraries.html

      Also, make sure you download the sample code to get started.

      Have fun!

  • SangPetualang

    finally i move the model to controllers .. and that’s all work ..
    thanks for your help :

    my controller:
    https://gist.github.com/1005585

    so now i just have controller and library

  • spondbob

    hi danny
    it’s so interesting reading your post, but i’ve a question. when i download the facebook-php-sdk from facebook developer, i got facebook.php file inside /src, but there’s a line that say : require_once “base_facebook.php”;. the base_facebook.php also present inside /src, but i didnt find the require_once “base_facebook.php”; on your post.
    i have problem with this thing because i cant resolve require_once in codeigniter
    thank you for any help

    • spondbob

      fyi :
      i’m using codeigniter 2.0.2 and php-sdk 3.0

    • Facebook released a new version of their SDK a couple of days ago. I am working on implementing it on CodeIgniter but it has been more complicated than I first thought. For some reason it is not picking up the session vars and I still need to do some testing before I update the instructions on this post.

  • Rob Mazoros

    spondbob :
    fyi :
    i’m using codeigniter 2.0.2 and php-sdk 3.0

    I had this problem for a while. The new FB library from the Git repo has two files not just the one Facebook.php from Danny’s original code example. Once I went back to the version Danny included with his code it started working, although my login button is in the wrong language.

  • Marcos

    Hello. Really nice library. I tried a lot, but this only, works with me. I got a issue. How can i logoff from PHP, without click on Logout button on page? I tried a lot of different solutios, but any works. Thanks!

    • I’d try this (not tested):

      $cookie_name = $this->facebook->getSessionCookieName();
      setcookie($cookie_name, ”, time()-9999);

      That will empty the cookie used for user identification. However, since its a cookie, you will still need to reload the page for it to work. Remember that cookie values are not refreshed until the page is reloaded.

      Have fun.

  • Nice explainer. Any progress with the new Facebook SDK? I’m getting: Fatal error: Call to undefined method Facebook::getSession() in /home/wmfox3/application/models/facebook_model.php on line 14

  • Pingback: Making Facebook php-sdk 3.0.0 play nice with CodeIgniter – Dash30()

  • Aza

    Thanks for all your hard work! Anxiously awaiting the next updated iteration with all of the new sdk bugs ironed out. Thanks!

  • Tamer

    So I have a weird issue trying to implement the facebook connect. I have rewrites working and everything seems to work fine but the issue is that I have to click the login button twice to get it to authenticate. Am I missing something in the configs? The link is http://www.tamerjmina.com.

    Any suggestions?

    • I tried your app and it works perfectly!. I clicked the login button once and I could log in and log out with no issues.

  • Tamer

    Danny Herran :
    I tried your app and it works perfectly!. I clicked the login button once and I could log in and log out with no issues.

    Looking at it again, I think I know what the issue might be. If I access the site as “tamerjmina.com” it stores the cookie under “tamerjmina.com” then it asks me to log in again when the url becomes “wwww.tamerjmina.com” so it stores the cookie again under “www.tamerjmina.com”. Do I need to force the page to redirect when someone accesses the site from “tamerjmina.com”?

  • Tamer

    This rewrite worked for me

    RewriteCond %{HTTP_HOST} ^yoursite.com
    RewriteRule ^(.*)$ http://www.yoursite.com/$1 [L,R=301]

    just FYI, if any others run into this issue

    Thanks Danny for the quick response!

  • Karl

    new sdk needs the file named “fb_ca_chain_bundle.crt”
    it can not work without it

    • Hi Karl. Not really, I’ve tried it and used it with no certificate and it works. But if you want cover your bases, just copy the certificate in the application/libraries folder and you’re set.

  • jan

    Do you have any idea why this is not working with the current head of CodeIgniter Reactor from the Mercurial repository? When I click on login I’m redirected to Facebook and I allow the App to access my data, after doing so I’m redirected to my app but I’m still logged out. If I use the 2.0.2 tag it works.

    • Hi Jan. No idea. I haven’t really tried the last commit of the CI Reactor. As far as I can see, it has to do with a base_url change. Once it turns into a stable version, I’ll give it a shot.

  • Gerard Nijboer

    Hi,

    When I authenticate the Facebook app to access my profile data, it redirects to my site, but the site keeps reloading.
    I’ve seen this with many CI-FB frameworks, how come?
    Can’t seem to figure out what goes wrong.

    Gerard

  • Gerard Nijboer

    Danny Herran :
    Facebook released a new version of their SDK a couple of days ago. I am working on implementing it on CodeIgniter but it has been more complicated than I first thought. For some reason it is not picking up the session vars and I still need to do some testing before I update the instructions on this post.

    Hi Danny,

    How is your example working with the latest release of the Facebook SDK?

    • Gerard, as stated in the main post, my example is already working with the latest Facebook SDK (3.0.1). Take a look at the main post.

  • ben

    Hey, thanks for this. Its certainly getting me a step closer to my aim. Could someone give me an example of how I would post to a users wall with this code though? Thanks

    • Ben, try this out and please let me know if it works:

          $attachment =  array(
              'access_token' => $this->facebook->getAccessToken(),
              'message' => "Hello, here is a post",
              'name' => "",
              'link' => "http://www......",
              'description' => "Write here your description",
              'picture'=> "http://www.yourserver.com/images/test.jpg";
              );
          //print_r($attachment);
          $this->facebook->api('/me/feed', 'POST', $attachment);
      

      This will post something to the users wall. Just add that piece of code to the your controller and replace the vars accordingly.

  • anil c

    Hi Danny,

    Thanks for this very useful post, i implemented it in my code and it’s working like a charm. but i am little stuck with two things:

    1) how to increase the scope of permissions while authenticating.
    i tried this:

    $config = array(
    ‘appId’ => ‘XXXXXXXXXX’,
    ‘secret’ => ‘XXXXXXXXXXXXXXXXXXXXXX’,
    ‘fileUpload’ => true,
    ‘scope’ => ‘user_birthday,friends_birthday,user_likes,friends_likes,user_location,friends_location,email,user_checkins,friends_checkins’,
    );

    $this->load->library(‘Facebook’, $config);

    But doesnt seem to be working.

    2) how to get access_token?

    i print_r($_SESSION) in my controller and got this:

    Array
    (
    [fb_170721186321213_code] => y7Zr2f1vXXXXXXXXXXXXXXXXXXXXXXXXXyL5
    [fb_170721186321213_access_token] => 17072118XXXXXXXXXXXXXXXXXXXXXXXXXprs
    [fb_170721186321213_user_id] => 12XXXXXXXXXXXX2
    [fb_170721186321213_state] => 60fXXXXXXXXXXXXXXe859
    )

    how to extract access_token from this.

    (this might be basic stuff but, i am very new to all, CI, PHP, and FB API… any help will be great. thanks

    • You edit the scope of the permissions in this line (model):

      $profile = $this->facebook->api('/me?fields=id,name,link,email');
      

      To get the access token you use this embedded function:

      $this->facebook->getAccessToken()
      

      Please read the model and the previous comments carefully. It is all explained there.

    • rhnkyr

      Still if we want to use this form, how can we manage the code?
      user_birthday,friends_birthday,user_likes,friends_likes,user_location,friends_location,email,user_checkins,friends_checkins

  • Philip Ashlock

    Thanks for providing this and keeping it current. This seems to work fine when I run it locally, but it stalls during the auth process when running it on a basic Dreamhost account. I’ve run into the same issue when using the facebook integration developed by elliothaughin (https://github.com/elliothaughin/codeigniter-facebook) and am trying to figure out the best way to debug because I don’t get any error messages (nor logs with threshold set to all). I just get a stalled auth process – it stalls when the url reads /?code=ms2CJz9TFO……&state=9d0c53…..

    I am however able to run the basic authentication example.php provided with the PHP Facebook-SDK.

    Any leads would be greatly appreciated. I don’t even know where to begin to debug without any error messages. I’m guessing this could be a CURL config issue, but that’s just a guess based on my limited experience with oAuth and Facebook Connect.

    Again, this seems to be an issue with the default Dreamhost environment since I don’t have any issues when running it locally. I am using different facebook app ids and everything for the local and remote versions of course and as I said before I am able to run the basic php SDK example.php fine on Dreamhost.

    • Philip, please make sure that you enabled the GET vars in your CodeIgniter config file. If the GET vars are not enabled, you wont be able to authenticate your users. As stated in the instructions: Facebook will try to pass the signed request via GET to your application. So, please make sure your CodeIgniter installation is set to allow the GET array. To do this, find the $config[‘allow_get_array’] in your application/config.php file and set it to true.

      Let me know if the problem persists.

    • Philip Ashlock

      Thanks for the suggestions. allow_get_array was already set to true. I currently have uri_protocol as AUTO, but have also tried PATH_INFO and others. My .htaccess looks like this:

      RewriteEngine on
      RewriteCond $1 !^(index.php|img|css|js|video_files|robots.txt|favicon.ico)
      RewriteRule ^(.*)$ /index.php?/$1 [L]
      
  • Chris Williams

    Hi Danny,

    Maybe you can help me out, I want my app to be able to “create_event” and “publish_stream”.

    it looks like it needs to be set here:
    $profile = $this->facebook->api(‘/me?fields=id,name,link,email’);

    What do I set to let facebook know I’m requesting those permissions?

    Thanks!

  • Alexander

    Hi Danny,

    First of all, thank you.

    2nd: I need to access the signed request of this app. I just need the uid of the visitor of my page, to check whether he likes my page or not.

    Anyway, the getSignedRequest() function doesn’t respond.

    I check it simply like this:

    $this->load->library(‘facebook’, $config);
    $sr = $this->facebook->getSignedRequest();
    print_r($sr);

    The problem is that $_REQUEST[‘signed_request’] just isn’t set. I test this by uploading it to my server and testing it in my iframe on apps.facebook.com/xxxx (it should be initialized when the app is loaded within the fb environment)..

    Gettin’ kinda hopeless here 🙂

    All the best,
    A.

    • Alexander

      Nevermind. I was doing a redirect, which clears the signed request. Thanks anyway.

  • Gerard Nijboer

    Hi!

    I don’t have the latest version of CI, I have version 1.7 or so.
    Would it still work or am I missing some vital parts?

    Gerard

    • Gerard, I haven’t really tested it on 1.7. I don’t think it works because the FB SDK needs GET vars that are not supported by CI 1.7. Upgrading to 2.0 is not difficult though 🙂

  • Matthew

    This only works for me where the Facebook Connect/Auth happens in the root/index action, ie: http://url/. If I change the auth to happen in eg, http://url/welcome/auth, it never logs me in (the fb session is never set).

    • Matthew

      after some debugging, it turns out my $_REQUEST[‘code’], or even the whole $_REQUEST array, is always empty so the FB SDK is unable to get the signed request, etc, etc

      The problem is the .htaccess lines from http://codeigniter.com/wiki/mod_rewrite/

      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php?/$1 [L]

      That ? in the last regex is causing the problem.

      Any suggestions for a fix? other than using a simple re-write like RewriteCond $1 !^(index\.php|php\.ini|phpinfo\.php|images|css|js|template|scripts|assets|robots\.txt)

    • Jayme

      Matthew :
      after some debugging, it turns out my $_REQUEST[‘code’], or even the whole $_REQUEST array, is always empty so the FB SDK is unable to get the signed request, etc, etc
      The problem is the .htaccess lines from http://codeigniter.com/wiki/mod_rewrite/
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php?/$1 [L]
      That ? in the last regex is causing the problem.
      Any suggestions for a fix? other than using a simple re-write like RewriteCond $1 !^(index\.php|php\.ini|phpinfo\.php|images|css|js|template|scripts|assets|robots\.txt)

      I’ve been having the same problem, when I log into facebook it redirects me to the original page, but I have to click log in again (it does not log in automatically). This happens for version 2.0.2 of CI.

      I will try having the redirect go to the base url, and see if that fixes it.

  • Andy

    Hey, sorry I’m new to CodeIgniter and have serveral errors if I implemented your code:

    A PHP Error was encountered

    Severity: Warning

    Message: Missing argument 1 for Facebook::__construct(), called in …/facebook/httpdocs/system/core/Loader.php on line 950 and defined

    Filename: libraries/Facebook.php

    Line Number: 37

    A PHP Error was encountered

    Severity: Warning

    Message: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at …/facebook/httpdocs/system/core/Exceptions.php:170)

    Filename: libraries/Facebook.php

    Line Number: 39

    and some other warnings

    Fatal error: Call to undefined function redirect() …/application/controllers/home.php

    Thanks for your help!

    • Andy

      ok I’ve loaded the library twice 🙂

  • Gerard Nijboer

    Hi,

    I’ve finally managed to set up the Facebook Connect on my existing CI-site.
    Now here’s a funny thing, I’ve successfully managed to enlarge the scope of the application to the following in the facebook_model:
    $profile = $this->facebook->api(‘/me?fields=id,name,link,email,gender,location’);

    The gender and location do indeed show up, but still not the email address.
    But I wish to get the user’s email address, how do I retrieve this?

    Gerard

    • Gerard Nijboer

      Found it, have a look at the file libraries/base_facebook.php, nearby line 455:

      @@@
      array_merge(array(
      ‘client_id’ => $this->getAppId(),
      ‘redirect_uri’ => $currentUrl, // possibly overwritten
      ‘scope’ => ‘publish_stream,email’,
      ‘state’ => $this->state),
      $params));
      @@@

      You should ask the user first before you may see his/her direct email address.

  • Pascal

    Hi there, I am quite new to both PHP and FB but have been trying to work my way through an implementation of the two.

    What I am currently working on is here…
    http://pascalwagner.com/newproject/

    Within my model I am attempting to do the following (I wanted to see if it was correct):
    $profile = $this->facebook->api(‘/me?fields=id,name,link,email,user_location’);

    Within my view I am attempting to output the information:

    The email works correctly but once I put the user_location in the model portion, I can no longer log into my application.

    I would also like to display a list of the current user’s friends…

    Is there a completely basic documentation of the implementation of FB and PHP together. I need it spoon fed to me. I have looked through Facebooks documentation but it doesn’t tell me WHAT code I need to write in PHP to implement the facebook codes. For this reason I am still confused on how to implement the two.

    • Pascal

      I also do not understand how to use the Javascript SDK or how to mix it with PHP. I have found out how to implement the Like and Login button using the Javascript SDK – but isn’t it double the work if the PHP is doing the same process (i.e. getUser() ).

    • Pascal, instead of ‘user_location’ use ‘location’.

      http://developers.facebook.com/docs/reference/api/user/

      The Facebook JavaScript SDK is not compatible with this library because the Facebook developers dropped the support for those features. Currently, there is a workaround that involves editing the FB PHP SDK but I have been really busy with work to finish it.

  • Gerard Nijboer

    Here’s another one:
    I’m trying to publish to my own Feed, I’m trying with this code:
    var_dump($this->facebook->api(‘/me/feed?link=ha&message=Woot!’));
    But my response is an empty array, instead of the corresponding ID.
    How do I post something to my wall?

    • Gerard Nijboer

      Alright, also that has been resolved, I guess I’m posting too soon:

      $publishStream = $this->facebook->api(“/me/feed”, ‘post’, array(
      ‘message’ => “I am doing some testing with Facebook SDK in CodeIgniter!”,
      ‘link’ => ‘http://dev2.besttopfives.com’,
      ‘name’ => ‘Facebook SDK & CodeIgniter’,
      ‘description’=> ‘And some description’
      )
      );
      var_dump($publishStream);

  • MugsMK

    Hi,
    I’ve been trying to figure out why I am getting the following error.

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Welcome::$session

    Filename: core/Model.php

    Line Number: 50

    I am new to CodeIgniter and to PHP so it’s a bit difficult to understand what’s going on. I tried to autoload the session library from config/autoload.php but it still doesn’t seem to work.Any suggestions would be greatly appreciated.
    Thanks for this wonderful post!

    • Gerard Nijboer

      Have you also set your $config[‘encryption_key’] in config.php?

    • Make sure your session class is initialized or auto-loaded and the encryption key has been set in the config file, just like Gerard suggested.

      If you are using database sessions, fill in the corresponding fields in your config file. Read this carefully: http://codeigniter.com/user_guide/libraries/sessions.html

  • Gerard Nijboer

    I wish to see which users are subscribed to my application.
    I’ve seen this page on the developer site:
    http://developers.facebook.com/docs/reference/api/subscription/

    And I’ve tried the following code:
    var_dump($this->facebook->api(“/137537702990550/subscriptions”));

    But this throws me the following error:
    Fatal error: Uncaught OAuthException: (#15) The method you are calling must be called with an app secret signed session

    Any knowledge on that part?

    • It depends on where you’re calling that line. The session must be initialized and the user must be identified in the system for it to work. I haven’t really tested that subscription object, so I am pretty much blind here.

  • Alastair Dewar

    Thanks for the wonderful tutorial!

    I feel like I’m so close to getting this app working.
    I’m having a problem with authentication. When the user clicks to login, it goes to facebook, where they verify and return the code and status through POST. However, my get_post function in base_facebook.php always returns false when looking for $_REQUEST[‘code’], even thought I know its definitely there.

    I have a suspicion that its CodeIgniter stopping it, so I’ve tried changing $config[‘uri_protocol’] with no luck. Could you shed any light?

    Thanks,
    Ally

    • Are you sure it’s sending the signed request via post? As far as I know it sends the request via GET. I haven’t really tried any post variant. Just make sure this setting is set to true in your config file: $config[‘allow_get_array’]

    • Alastair Dewar

      Sorry, yeah, your right enough in saying that. The requests are sent via GET. I already have that set to true in my config.php

      Do you think my .htaccess could be causing me problems?

      Thanks for the quick response!

    • allow_get_array did not do enough for me. I would still get errors about invalid characters in my URL from CI. I had to set uri_protocol to REQUEST_URI and that got it working for me.

      I am running PHP 5.3 with Fast CGI on a shared hosting platform.

  • patrizio

    Hi danny,

    At last did you manage to modify the FB PHP SDK in order to add FB cookie support?

    I’m trying to implement FB login in PHP and using the standard login an logout has the following drawback:
    Starting from a state of logged out, if I log first in FB home page and then go on my web site and refresh the page I result still logged out until I click on the login url.
    Using the JS SDK instead I result logged in.
    I guess this is because PHP SDK isn’t able to read the FB cookie.

    What I’m trying to do, and at the moment I’m using a mixed approach JS/PHP without much success, is consider an user already logged in when reloading my site.

    Do you have any tip, info or code to share with me??

    Help would be very appreciated.

    Thank you very much

    • Hi Patrizio. I am working in a variant of the SDK with cookie support, however, I haven’t had much time to finish it. In the meantime the only way to login and logout is with the specified links. As soon as I finish the integration with cookie support, I’ll make sure to publish it here. Have a nice day.

  • patrizio

    Danny Herran :
    Hi Patrizio. I am working in a variant of the SDK with cookie support, however, I haven’t had much time to finish it. In the meantime the only way to login and logout is with the specified links. As soon as I finish the integration with cookie support, I’ll make sure to publish it here. Have a nice day.

    If you want I can help you with that. I can partecipate in writing the code or even as a simple beta tester

  • muhammedck

    thanks! i’ve just downloaded.

  • that horrible..
    i can’t use it because iam newbie in ci..
    sob..

    okey..
    i’ll try again 😀

    • Danny Herran

      Download the sample code and give it a try. It will get you started. 🙂

  • neo

    hi,

    first of all thankxx for the tutorials 🙂
    coming to my problem:

    i want to know how long a user is online. for example i want to have this as a result in my database:
    user:neo date:2011,07,19 online_presence= 4 hours
    So i was on 19.of july 4 hours only in facebook.

    There is a permission in the API called: user_online_presence.
    The problem is, this gives me only a boolean value 🙁

    Is there any way to retrive this kind of information?
    Maybe with the chat-api !!!

    thankxxx alot
    best regards
    neo

    • Wow, you got me on that one. I really don’t know how to identify for how long an user has been online using the FB SDK. I mean, how can we detect when the user closes the window? You can actually start a session var when the user logs in and then check the timestamp difference when the user logs out. This would only work if the user ever logs out though, because sometimes they just close the window.

  • Gary

    Hi when I try to use this i get a page 404 with this in the address
    APPLICATION_URL/index.php/login

  • Gary

    I updated my facebook.sdk but it still gets a 404 and its coming from here

    redirect(‘login’);

    • Probably you have a misconfigured routes.php. If you could upload the project somewhere, I’d be glad to help you out.

  • Hello all,

    It’s not working, please help..
    The problem is after logging in to facebook, it will redirect back to site and not logged in, with a request code..

    How can I fix this?
    link: http://www.dailydealso.com.au/facebook_test

    Warm regards,
    Reland

    • I checked the URL and it seems like CI is not grabbing the GET vars. Please make sure your CodeIgniter installation is set to allow the GET array. To do this, find the $config[‘allow_get_array’] in your application/config.php file and set it to true.

  • pana emil

    Hy Danny! Thanx for the tutorial and coding. I have the same problem mr. Reland Pigte have. The address is http://www.matchifier.com/welcome
    The allow_get_array is true, the sessions are loaded in the model. Can you tell me why isn’t it working ? 🙁

  • pana emil

    Hello again! I found a fix for my problem that a logged user is redirected to a page that don’t see it logged in. It’s very simple: the redirect url when you log in must be the first page of your application, the controller set in your routes.php as first page. I personally changed in getCurrentUrl() function the line below:
    $currentUrl = $protocol . $_SERVER[‘HTTP_HOST’] . $_SERVER[‘REQUEST_URI’];
    with:
    $currentUrl = $protocol . $_SERVER[‘HTTP_HOST’] . ‘/index.php’;
    Now it works! Please tell me if it’s working to you!

  • Egemen

    I have been struggling with solving a problem of “log out”. I’m using your codes, it works in my setting apart from “log out”. when clicking log out, it logs out facebook, but it doesn’t log out from my site. As if i didn’t log out, i can walk around in my site. Site is : http.//hatirnaz.turkemedya.com

  • legendxx89

    I use the method:
    $friends= $this->facebook->api(“/$user/friends”);
    and properly receive friends
    but if use:
    $likes = $this->facebook->api(“/$user/likes”);
    I get an empty object
    why?

    ps:
    I also tried with the url as written here:
    https://developers.facebook.com/docs/reference/api/
    with the same result

    help please!

    • legendxx89

      ok I solved it was only a matter of the application permits

  • Michiel

    legendxx89 :
    ok I solved it was only a matter of the application permits

    Hey,

    you said something about application permits, maybe you or somebody else can help me. I try the following to change the application scope (as of sdk 3.0), but it doesn’t want to work.

    $fb_data = array(
    ‘me’ => $profile,
    ‘uid’ => $user,
    ‘loginUrl’ => $this->facebook->getLoginUrl(array(‘scope’ => ’email, publish_stream, user_birthday’)),
    ‘logoutUrl’ => $this->facebook->getLogoutUrl(),
    );

    even changing the loginUrl to a plain string ‘myLittlePinkBunny’ doesn’t work. Looks like for some reason the loginUrl is generated elsewhere and not in the Model as described in the tutorial.

    Hope someone can help me!

    Thx M

  • chuch

    Dear all,

    I have one problem with facebook connection.
    when I click on login it go to login normally, but after I logined it redirect to my site.
    the problem is I see login the same, until I click on login again I can see “Hi my name” and photo and can logout.
    Please any one help

    regards

  • I’m noticing the same log-out issue. It’s not clearing the fb_data array in the session and keeping me logged in on my site even though I’m no longer logged into Facebook. I tried even unsetting that array in my site’s normal log out flow and it persists! I’m wondering if it’s because the library is being auto-loaded and overriding my session unset. Either way it’s one of those maddening bugs. Otherwise I got this working first go round and it’s great!

    Thanks for any help on this one!

    • ajit

      Hi

      I am also having same issue. Can’t logout. Could you be more specific how you solved this issue.

      Thanks
      Ajit

  • Marques

    If you are having problems getting the Access token back after logging in, I had to change base_facebook.php and replace all $_REQUEST with $_GET. Somehow that fixed it. Specifically the getCode function, after logging in it always had the code and state in the URL, yet wasn’t getting it with REQUEST. Hopefully this helps

  • Matthew

    Has anyone had problems after updating to PHP SDK 3.1.1? I’ve reverted to 3.1.0 (which doesn’t work with JS SDK), because 3.1.1 with CI would never detect the user as connected.

  • jan

    Danny Herran :
    Once it turns into a stable version, I’ll give it a shot.

    As CI 2.0.3 has been stable for a while I still see the same strange behavior. If I switch back to CI 2.0.2 it works, with CI 2.0.3 it doesn’t. Has anyone got an idea? When I click on the “Login with Facebook” link I’m re-directed to my application and still logged out.

  • I have to start a new project soon that will be based on the new CI version and also the new FB SDK version. I will test everything and post the update as soon as its finished. Sorry for the delays.

  • I have uploaded files that u have provided. It isnt working for me.
    You can see that here : http://apps.facebook.com/testciapp/

  • Vishal Rathod

    Thanks a lot , it helped me a lot. 🙂

  • Robi

    I am having the same problem as chuch above. I can login but it seems flakey.

    Sometimes I hit login, I am sent to the facebook site, login then get redirected back to my test site (on localhost) and i am logged in fine.

    Other times I do exactly the same but when i get redirected back to my site i see the login button still. I click it again and the page reloads and I can see my user data.

    Any idea whats going on? I tried replacing all $_REQUEST in base_facebook to $_GET but it didn’t make any difference.

  • Thank you. Very helpful

  • Dustin

    I have the Facebook javascript sdk and facebook php sdk working with codeigniter somewhat.

    If I login with the javascript sdk I have to refresh the browser once and all the facebook data is there. The javascript has the page reload, but that is not enough. I have to physically hit the refresh button on my browser.

    If I can just figure out why the page needs refreshed twice to get the data then my app would be ready to roll.

  • Pingback: Making Facebook php-sdk 3.0.0 play nice with CodeIgniter | billfox3.com()

  • seb

    Hello.
    it doesn’t word with php sdk 3.1. getUser return null. Someone has a solution?

  • Jon Mears

    Excellent stuff, works a treat! I appreciate you spending the time and effort to put this online.

  • Hey thanks for the well defined tutorial.

    Ive implemented the same in my project.

    My problem is that authentication is working perfect on my local server.

    After implementing on hosting server im facing one problem that is :-

    from base url ( http://jumbotv.in/nib/ ) authentication is working properly but when im trying to make it from another controller its not working, not getting session.

    Just visit the URL and you would know the situation.

    Kindly Respond me ASAP 🙁

  • Thanks alot! You’re the bomb! I am just starting on code-igniter and this helps a lot!

  • Mohan Wiki

    Thanks for your tutorial. It is very useful to me. Specially this line.
    CURLOPT_SSL_VERIFYPEER => false, 🙂

  • adi

    Danny Herran :
    I checked the URL and it seems like CI is not grabbing the GET vars. Please make sure your CodeIgniter installation is set to allow the GET array. To do this, find the $config[‘allow_get_array’] in your application/config.php file and set it to true.

    Hi Danny, i try to set $config[‘allow_get_array’] = true, but this can’t grabbing the get vars.

    When i access http://inibayiku.com/cifb/

    it can grab the vars,

    but when i access http://inibayiku.com/cifb/welcome

    it can’t grab the vars..

    can you help me, why the problem ??

  • Carlo van Herwaarden

    Hi,

    everyone with the “I have to login twice problem”. It has something to do with the the not unsetting of fb_appId_state. I haven’t figured out what the problem was but this small hack in facebook_model.php solved it for me.

    If you add this just before the end of the script

    if(isset($_REQUEST[‘state’])){
    unset($_SESSION[‘fb_’.$config[‘appId’].’_state’]);
    }

    so just before

    $this->session->set_userdata(‘fb_data’, $fb_data);
    }
    }

  • Hi There,

    First off thanks for the tutorial it helped a lot. However I found that by changing the filename ‘facebook.php’ to ‘Facebook.php’ didn’t work out so well for me. I just kept both the file and the library load ($this->load->library(‘facebook’, $config) all lowercase and then it started working.

  • Getting this Error!

    CI Error:
    A PHP Error was encountered
    Severity: Notice
    Message: Undefined property: Home::$session
    Filename: core/Model.php
    Line Number: 50

    PHP Error:
    Fatal error: Call to a member function set_userdata() on a non-object in /application/models/facebook_model.php on line 42

    • Bojan

      You have to autoload session library. I had the same problem as you have.

  • Yura

    Works great! Thanks a lot!

    The issue with logout is solved like this:

    1. In View:
    <a href="home/logout/”>logout

    2. In Controller (home.php):
    function logout($fburl)
    {
    session_destroy();
    redirect($fburl);
    }

    This worked for me.

  • Damon Poole

    Just a heads up, I had trouble with this because CI was stripping data from $_GET and $_REQUEST and placing it in the input class, meaning the facebook API couldn’t receive the facebook login reply. If you have these problems, you’ll have to replace facebook’s calls to $_REQUEST with calls to CI’s $this->input->get();

    Thanks for the script though.

  • rowgm

    Marques: It worked! I debugged the app and $_REQUEST has been altered by Codeigniter. I changed $_REQUEST by $_GET in all the code and it worked!

  • Asja

    Thanks a lot! U helped me!!!! =))

  • Yasmine

    hello, i just can see a empty page, i don’t know what is wrong! Any ideas?
    I’m using the new version CI and PHP SDK.

    • Ala’ Yasin abuhijleh

      Yasmine. Though showing errors in enabled on the application level, it might not be on the php.ini. Which prevents errors from showing. To fix this issue do the following

      on the index.php on the root add the following line:

      ini_set(‘display_errors’, 1);

      So the case ‘development’ should be something like this

      case ‘development’:
      error_reporting(E_ALL);
      ini_set(‘display_errors’, 1);

      Now you’ll start getting errors and you’ve to start fixing them ;).

      best of luck

  • Yasmine

    hello, I identified that my problem are in the line on my model, but yet don’t know how I can do it works:
    $this->load->library(‘Facebook’, $config);
    if I comment this line the view shows a error message, but when uncomment this line the view shows a blank page.

    • The error is most likely due to a missing library or any problem with the configuration. In order to easily identify the problem, I’d suggest you to enable development mode on the index.php file of your CI installation.

      A blank page means an error that php is not displaying because of the error_reporting configuration of your index.php file.

  • Yasmine

    I’m using php -sdk 3.1.1 and CI 2.1.0

  • Yasmine

    My CI it’s already in development mode and still I get a blank page

  • Anonymous

    Hello! Your code helped a lot! Thank you!

  • Mikey

    Hey Danny, thank you so much for the tutorial. I went through many tutorials and this one seemed to be the most promising.

    I followed all your instructions (and even some added in the comments) but sadly, I’m still unable to get the login to work and I’m not too sure why. My getUser() function still keeps returning 0, even though I’m logged in on Facebook and have approved my application (which happened after I clicked the login button). From what I read, it has something to do with my sessions being saved? I have always been using CI Session and there has not been any problems, so I’m not too sure if it’s session-related.

    Currently, the only thing that happens after I click the login button is that these characters “#_=_” get appended to my URL.

    I would greatly appreciate your input.

    • Mikey

      Ah problem fixed finally.
      1) Make sure the redirect URL is not redirecting to somewhere else. For example, I am using Tank_Auth, so I was redirecting auth/index to auth/login;
      2) Change $_REQUEST[‘state’] and $_REQUEST[‘code’] to $_GET[‘state’] and $_GET[‘code’];

      Thanks Danny & commenters!

  • abbas makakula

    You’re the man, thanks!!

  • johnny

    The only way I could figure out how to fix the must log in twice problem is to add this to facebook_model.php

    if(isset($_REQUEST[‘state’]) && !$fb_data[‘uid’]){
    redirect($fb_data[‘loginUrl’]);
    }

    right before this line

    $this->session->set_userdata(‘fb_data’, $fb_data);

  • Pingback: 10+ Useful PHP Facebook Login Connect Tutorial : Daily Syntax()

  • Pingback: GUIDE: Facebook Login with CodeIgniter | Ala' Yasin Abuhijleh()

  • NV

    Hey! Thanks so much for posting this!

    I’m trying to save additional user data in the session and it seems that loading / adding the Facebook_model model wipes out any additional data that I try to store in the session. (ie: between consecutive reloads of the page any data I stored with $this->session->set_userdata(‘userid’, 9) does not get saved)

    Have any of you seen this problem / have any ideas on what to do?

    Thanks!

    ‘9kwuh

    • Have not seen that problem before. The only issue I had with sessions on CI in the past was because my sessions table wasn’t up to date with the latest CI version. Make sure you’re using the latest table structure so the session data can be saved properly.

  • Tom

    Hey thanks for this, looks great. I just have a few questions if anyone has has time to answer:

    – Is the login checked with Facebook every time Facebook_model is loaded? Yes?
    – Is the login checked with Facebook every time $this->session->userdata(‘fb_data’); is called? No?

    Basically just trying to keep load times down as much as possible. So essentially I can only load Facebook_model once to set the session data, then use $this->session->userdata(‘fb_data’) whenever I want to use their Facebook details, and only have to call Facebook_model when I want to refresh their FB status?

    Sorry – just getting used to working with Facebook. I noticed loading Facebook_model adds about 1 second to render time for the app, so i only want it to talk to FB when I really need it to.

    I hope that all makes sense!

    Many thanks,

    Tom

    • Yes, in theory, you’re right. However, if you don’t constantly check against the Facebook SDK for a valid FB Session, you could probably end up with broken user information. There are a couple scenarios that could happen while the user is browsing your website:

      a) The user logs out of Facebook from another window. You must know that as soon as your website refreshes.
      b) The user drops the app permissions from their FB account in another window or browser. You absolutely need to detect this and act accordingly on your next page refresh; only if you need special permissions on your app.
      c) The Facebook session expires for that browser (cookie). As soon as your website refreshes, you need to ask for the login information again.

      If any of those scenarios is present and you’re not validating the user-data against the FB SDK, then you might end up with a broken app. Probably asking the user to perform actions that can’t be completed without a valid FB session or ever requesting information that is just not there.

      Yes, pulling info from the FB SDK is slow and will affect your response times. However, there are some cases where you don’t need to check for a valid FB session, like on static pages, home page, contact us page, etc.

      Have fun!

  • Please try the updated code sample. It should work out of the box.

  • That’s an internal FB error. Please check that you’re passing the right parameters to the Facebook SDK. If you’re using a wrong app-id, app-secret or app-permissions, FB will give you some errors here and there.

  • Subhra

    Danny Herran :
    That’s an internal FB error. Please check that you’re passing the right parameters to the Facebook SDK. If you’re using a wrong app-id, app-secret or app-permissions, FB will give you some errors here and there.

    I have checked it. Everything is right. But don’t know why it’s not working. Will I need to keep the site url (in fb) and redirect url identical?

  • NV

    Hey Danny,

    Thanks again for the article! I ended up having to strip out codeigniter sessions as they weren’t working but i got it working with base PHP sessions.

    I”m having one issue with the facebook logout:

    1. Log in to my app or fb (either)
    2. Log out of facebook
    3. My app successfully logs out
    4. when I try to log in again, nothing happens now.

    Any ideas on what is going on? I just keep getting redirected back to the original login page with some weird character at the end of the url. Thanks in advance!

  • logout issue try to use javascript FB API

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

    it working fine for me.

  • James Tan

    Thanks! I struggled for hrs for that fix and your suggestion works. Was getting getUser() result 0 until I set $_REQUEST to $_GET.

    Marques :
    If you are having problems getting the Access token back after logging in, I had to change base_facebook.php and replace all $_REQUEST with $_GET. Somehow that fixed it. Specifically the getCode function, after logging in it always had the code and state in the URL, yet wasn’t getting it with REQUEST. Hopefully this helps

  • Hey! Thanks so much for posting this!

    Message: Undefined property: auth::$session

    Filename: core/Model.php

    Could you have any idea why it’s not working?

  • Steff

    HI – I am having trouble getting my site to logout. It runs through the fb logout url and then lands back on my initial login page, but the session still exists. So the site still thinks that I am logged in. Is there a way to dump the session and then send the user to the fb-logouturl page?

    I didn’t quite understand Yura’s post (January 25th, 2012 9:48am)

    cheers!

  • sethumadhavan

    this one is working for me….

    i added one method in facebook_model like

    public function fbLogout()
    {
    $this->facebook->destroySession();
    }

    and added logout method in my controller

    function logout()
    {
    $this->facebook_model->fbLogout();
    $this->session->sess_destroy();
    $this->session->userdata = array();
    redirect(‘login’);

    }

  • Cosmin

    I’m struggling with the same problems for a few hours now, and nothing works.
    If I use the method in the tutorial it logs out from FB, but it doesn’t destroy the session on the page, so I it displays logout instead of login.

    If I use session_destroy() it works, but it doesn’t destroy the fb session.

    sethumadhavan unfortunatly your method doesn’t work for me. it doesn’t logout from facebook, neither from my page.

  • Pim

    I also had the problem of the session which keep existing.

    Sethumadhavan’s solution didn’t work directly for me, since the Facebook object doesn’t have a method called destroySession()

    So what I did was making the clearAllPersistentData() a public method and calling it from the Facebook_model->fbLogout()

    Bad practice? Perhaps. But solved it for me.

    • thinkdj

      I’d downloaded the latest SDK when I started with this tutorial and it does seem to have destroySession();

  • Brynleif

    Thank you very much for having uploaded this and for keeping it updated. I would be pretty lost without this. I am having a problem that I am unable to understand, I hope someone here would like to help me out.

    I have managed to log in to the CI-page with Facebook and I can see the username and the picture. So far so good. Everything I need seems to be stored successfully in the CI-session. But when I open the topsecret function in the welcome-controller, this data doesn’t seem to exist. The function begins with $fb_data = $this->session->userdata(‘fb_data’);, but when I echo $fb_data[‘uid’] I get 0. I go back to the welcome page, and everything works perfectly.

    Sessions are auto-loaded, so I don’t understand what is causing this. Does anyone see what I am missing?

    Thank you.

  • Kamaldeep Singh

    Hi Danny,

    Thanks for updations.I am creating facebook login app with Codeigniter.Login functionality is working fine with codeigniter but when m clicking on logout url(facebooklogout url),created url is fine (means all params are containing in url) but its redirect to me facebook.com and session doesnot destroyed.
    I had tried manually delete session by calling facebook->destroySession but this will delete facebook session from my site but not from facebook.com.
    Please provide me its solution.Its urgent basis for me. Thanks in advance.Hope you can understand my problem and try to give solution to me

  • SImon Barker

    Hi Danny,

    This tutorial has been invaluable in getting facebook login working on my side project so thank you for writing it, but I am having issues making the session data persist.

    The only way that I can make the $fb_data persist is to load the model in the construct of my controller class. This means that operations which work regardless of weather a user is logged in or not are slowed up by the GET requests made by the facebook class.

    This is a pain and means that I have to load the class on an as needed basis, rather than just for login and log out. Otherwise the session data does not persist. Why does the facebook session data not persist and can this be changed?

    Also, I noticed that when using this class the session ID is updated on every page refresh but not if it is removed.

    Any help in solving this issue would be great.

    Simon

  • Kriss

    Everything is working fine apart from “Logout”, The logout link does not destroys the session. Does anyone has some idea?

  • pawel

    The login doesn’t work – It’s just linking to the current page – why?

    • Abhijit

      Hi Danny.

      I am also getting same issue.It goes to Facebook App.After approval it comes to login page again.

      When I print_r($fb_data) $fb_data[‘uid’] is set to 0.

      I am not able to see picture or logout link.

      Thanks in advance.Please Help

      Regards,
      Abhijit

  • Prabin Shrestha

    I am having the same problem. can someone help me out from this?

    Brynleif :
    Thank you very much for having uploaded this and for keeping it updated. I would be pretty lost without this. I am having a problem that I am unable to understand, I hope someone here would like to help me out.
    I have managed to log in to the CI-page with Facebook and I can see the username and the picture. So far so good. Everything I need seems to be stored successfully in the CI-session. But when I open the topsecret function in the welcome-controller, this data doesn’t seem to exist. The function begins with $fb_data = $this->session->userdata(‘fb_data’);, but when I echo $fb_data[‘uid’] I get 0. I go back to the welcome page, and everything works perfectly.
    Sessions are auto-loaded, so I don’t understand what is causing this. Does anyone see what I am missing?
    Thank you.

  • nicky

    it never logout

  • amard

    logoutUrl only logout user from facebook account, it does not clear your site session data. you need to call codeigniter sess_destroy()

    • David

      Hi, I have tried this, and still can’t seem to get the logout function to work as I expect. I expect it should reload the welcome view (through the index function in the welcome controller) and show the login link once again.
      When I click the logout link, yes I get logged out of fB, and yes the welcome page reloads, but it still shows the link to the secret page.
      Any ideas?

  • Bohara

    A PHP Error was encountered
    Severity: Notice

    Message: Undefined property: Welcome::$session

    Filename: core/Model.php

    Line Number: 51

    Fatal error: Call to a member function set_userdata() on a non-object in C:APM_Setuphtdocsapp_nameapplicationmodelsfacebook_model.php on line 47

  • Pete

    To fix logout you can simply add a new controller which will be the same as the 1st one only that you can add a new function:

    function logout()
    {
    session_start();
    session_unset();
    session_destroy();
    session_write_close();
    setcookie(session_name(),”,0,’/’);
    session_regenerate_id(true);
    redirect(‘welcome’,’refresh’);
    } // end of logout

    Also you need to fix the views so as to call the new controller’s function:
    NEW_CONTROLLER_NAME/logout

    and remove or comment out the load of the model:

    $this->load->model(‘Facebook_model’);

  • Pingback: codeigniter x fb connect | code@butterflybone()

  • Agencja interaktywna CRENEO

    Thank you very much – we use it in many projects for our customers.

  • Ryan

    I also get blank/0 $this->session->userdata(‘fb_data’). Any solution? This worked once and then never worked again, although the code didn’t change.

    • Ryan,

      Try and update the SDK. Download it again from Github and give it a shot. That SDK has changed recently. However, the CodeIgniter code should remain the same.

  • Tom

    Hi Danny
    Thanks for this – great work.

    Will this work if I combine the JS SDK for login and the PHP SDK for the rest? If so could you give me an example?

    Cheers

  • Szymon Miałkas

    Thanks for this, it was very useful.

  • ardi

    hey danny.. the code is work at localhost but when i am implementing at app facebook its not working..the uid return 0 and me profile is null…any solution??

  • ardi :

    hey danny.. the code is work at localhost but when i am implementing at app facebook its not working..the uid return 0 and me profile is null…any solution??

    This happened to me a few days ago in an old app. It was because I didn’t have the latest Facebook PHP SDK and SSL certificate installed. Can you please download and install the latest SDK? Also make sure you are using sessions, that the app URL is properly configured on Facebook and that the app permissions have been accepted.

  • ardi

    hmm..i already use latest facebook php sdk and i already check ssl certificated have successful installed. maybe the problem is session, or app configuratuin

  • ardi

    any solution danny? how to make sure i’m using sessions properly and app url is properly configured?

  • ardi

    if my app Curl enabled can make this error solved??because my app curl is not enabled now??need answer 😀

  • Yasir Hussain

    Thanks for such a nice and up to date article. helped me save alot of hours 🙂

  • Rod

    Danny,

    I’m having the next problem

    If i use the login example (http://www.kaltin.com/index.php/example
    ) first time i had an error HTTP 500 error
    Module FastCgiModule
    Notification ExecuteRequestHandler
    Handler PHP via FastCGI (*.php)
    Error Code 0x00000000

    if i refresh the page i saw the fb session

    I had my CI config with $config[‘permitted_uri_chars’] = ‘a-z 0-9~%.:_-#_=_’;
    $config[‘allow_get_array’] = TRUE;

    Latest CI and Latest FB SDK

    Any help? sorry for my english

    • Hello there. This is an IIS7 specific error handling the GET variables in your request. I tried it myself, and when you drop the variables, it works just fine. I am not an IIS expert myself, so there isn’t probably much information I can provide. I would contact my hosting provider with the full error description so they can sort it out.

  • Rod

    Thnks Danny i really appreciate that!

  • Rodrigo

    There were an error with the PHP version, we change the FB SK to the version 3.0 and we solved

    Thankyou Danny

  • renz

    it shows blank in my facebook how to fixed this i already change the sdk.

  • Theavuth

    I have an error with this message, who can assist me?

    The redirect_uri URL must be absolute

    Thanks in advance

  • Facebook Covers

    It’s really helpful tutorial. thank you for sharing.

  • Pingback: How can I get the interests of my friend through facebook api? - PHP Solutions - Developers Q & A()

  • Cliff

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to
    my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was
    hoping maybe you would have some experience with something
    like this. Please let me know if you run into anything. I truly enjoy reading
    your blog and I look forward to your new updates.

    • Take a look at AI Twitter Feeds for WordPress. Does the job.

  • Franklin

    Hi, I’m working with Codeigniter. I’m usign facebook login. I did the same as you mentioned above. But not able to login into my webiste. If I print the fb_data then it returns array ‘me’ => null and ‘uid’ => 0. kindly help me to fix this issue.

    Thanks in Advance.

  • Franklin

    Hi,

    I’ve fixed the previous problem. No I need one help. If I login in my website using facebook, I need to fetch the users details to store them in my db. It’s working. But for some facebook accounts, it can easily fetch the details such as name, email etc. But for some accounts it couldn’t able to fetch the email. I can get all the details except email for some accounts only. So please help me to find solution and solve this problem.

    Thanks.

    • Franklin, it happens sometimes because the SDK can’t get the user data. When this happens you have 2 options: You could do a loop in your code, if the data is not there, loop 3 times to request the API again using $this->facebook->getUser(). Another way is to let the user know that their data couldn’t be retrieved, so refreshing the page with any button would do it. Also make sure your sessions are configured properly.

  • Excelente post Danny. Hoy en día sigue siendo de gran utilidad para muchos. Saludos!

  • Rui

    What should be the behaviour when user login in FB through the website, but after that logout from the FB website?
    In my opinion user should also logout from the website. I’ve tried this example but after logging in, getUser() method always returns a valid user (even if logged out in FB).
    More details in here http://stackoverflow.com/questions/20033336/facebook-php-sdk-getuser-returns-a-valid-userid-after-logout-from-facebook
    Can someone help?

    • I replied to you on StackOverflow. Take a closer look at my code. You need to test if the API has a response and then update $user appropriately.

  • Rui

    I replied back. For how long should be expected to get the ID even after logging out from Facebook manually?
    Was it supposed to be like this?

    • Actually it is intended to be like that. The piece of code that I posted is coming straight from the FB example they had in Github. Somehow, the user ID is there most of the time, so in order to be completely sure, you need to make an API call, if there is no response, then you reset the user ID to null.

  • Rui

    Ok, thanks a lot for the support.
    Keep up the good work!

  • Rui

    Just re-tested this and even after waiting a few minutes and user appears to be always logged in on Facebook. Don’t know exactly if I’m missing something, or eventually a bug on FB SDK or CI.

  • vishal

    hey danny !, nice post ,. thanks a lot
    but i am getting uid=> 0

    Array ( [me] => [uid] => 0 [loginUrl] => https://www.facebook.com/dialog/oauth?client_id=some value&redirect_uri=http%3A%2F%2Flocalhost%2Fcards%2F&state=1cef569a0b18210693a4d534e46694d1&scope=email%2Cuser_birthday%2Cpublish_stream [logoutUrl] => https://www.facebook.com/logout.php?next=http%3A%2F%2Flocalhost%2Fcards%2F&access_token=some value )

  • Hi danny, I am currently testing on localhost and I am getting the 0. Please let me know if this is because I am running it on localhost. Thanks

    • Danny Herran

      Yep, you need to test it in a public server. It wont work properly on localhost.

  • hey danny !,
    I have problems,

    i am getting uid=> 0

    [me] => [uid] =>

    • Hi Pablo, have you tried testing it in a public server? the uid 0 issue is usually related to localhost testing.

  • vibhav

    sir, every time i logout it get logout but the session is still saved in my website how to remove this problem.

  • You deserve a nobel prize for this article!! Keep going man!

  • priya

    hi i m getting The parameter redirect_uri is required error please will u help me i m new to codeignter

  • Mayur Makwana

    The parameter redirect_uri is required