A Very Simple and Easy to Understand Method of integrating Facebook Login to your site

This is more or less the most modern method as of 2011-May and as far as I understand it will work come 2011-September when OAuth 2.0 is mandatory.

Code for the login page:

<!-- stock code for asynchronous (to avoid lengthy page loads) loading of FB Javascript SDK -->
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  window.fbAsyncInit = function() {
    FB.init({appId: "YOURAPPID", status: true, cookie: true, xfbml: true});
    FB.getLoginStatus(
      function(response) {
        if (response.session) window.location.href="http://www.yourdomain.com/already-logged-in.php"
      }
    )
  };
  ( function() { var e = document.createElement('script'); e.async = true;
                 e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
                 document.getElementById('fb-root').appendChild(e); }() );
</script>

<!-- actual code for displaying the button -->
<fb:login-button onlogin="window.location.href='http://www.yourdomain.com/already-logged-in.php'">
  Login with Facebook
</fb:login-button>
    

PHP-based code to determine from server side which authenticated user is currently logged in:

When a user has already logged into your app/website via facebook, a cookie fbs_YOURAPPID will be present. This cookie has the access_token your app needs to query the Graph API for various data. In this case, you would want to call https://graph.facebook.com/me to get info on who is logged in.

parse_str(substr($_COOKIE["fbs_YOURAPPID"],1,-1),$fbAppCookie);

$handle=fopen("https://graph.facebook.com/me?access_token=".$fbAppCookie["access_token"],"r");
$whosLoggedIn=json_decode(fread($handle,99999));

print_r($whosLoggedIn);
    

Note: json_decode is available by default only starting from PHP 5.2. If you are on PHP 5.1, you must install the json extensions. One of the easiest ways would be via PECL for those with control over their PHP environment (e.g. on VPS or dedicated server). Basically, just do:

# pecl install json
on your ssh command line.







Back to Tutorials