Other sites run by Goldstein Technologies: RealFoot | QGenix | ZingJet | SkyDroid | Paul on Golf |

Facebook Connect Tutorial


Login Page

This is the page where users will login to your site. For people that are not using Facebook to login, it will have a username and password form (or whatever you use for your site). For Facebook Connect users it will have a button allowing them to "Connect" to your site using Facebook. The page also supports automatically (no user action) logging people into your site if they have already authorized your site through Facebook and if they've created a user account on your site and linked their Facebook account to it.


Step 1

Instantiate the php Facebook client and get the user's Facebook id if available (same snippet as on Logged in User page).

include_once 'site/fbconnect/config.php'; //has $api_key and $secret defined.
include_once 'site/facebook-platform/client/facebook.php';
global $api_key,$secret;
$fb=new Facebook($api_key,$secret);

Note that get_loggedin_user() will not return anything unless the user is logged into Facebook, has connected/authorized your site, and the Facebook Connect Javascript objects have been initialized at some point in the user's browser session. Since it is likely that this is the first page the user is hitting on your site (or got redirect here because they were not logged in), then get_loggedin_user() will most likely not return anything because one or more of those steps have not happened. Later in the page, however, we will see how this page gets reloaded, which will then enable get_loggedin_user() to return a value.

Step 2

If $fb_user is populated, then query your database to see if this facebook id is already linked to a user account. If you get a result, then LOG THEM IN! If you don't get a result, then send them off to the Connect Account Page so that they can either link their Facebook id to an existing account on your site, or create a new account using data from Facebook.

if($fb_user) {
	//Query your database to see if the $fb_user exists
 	$dbconn=connectdb(); // you can use whatever database connection and query techniques you normally would use.

 	//you'll have to modify this query for your own database
    $query="select id from userprofile where fb_userid=$fb_user";

	//if you get a row back then : Log the user into your application by setting a cookie 
	//or by setting a session variable or whatever other means you like or use.
	// then send off to the logged in user page:        
	if($result && @mysql_num_rows($result)==1) {
    	//you can also optionally set their user id (your sites id) in the session as well if you need to  	
    	//After setting session values, forward them off to the Logged in User page.
    	header("Location: http://www.yoursite.com/loggedInUserPage.php");
	} else {
		//user is logged into FB and has authorized yoursite.com for connect. But
		//we don't have their fb_user id stored on yoursite.com database yet.		
		//so send them to the Connect Account page so they can either link up with an 
		//existing account or create a new one.
		header("Location: http://www.yoursite.com/connectAccount.php");

Step 3

Just like in the Logged in User page, we need to load the required Facebook javascript library.

<script src="http://static.new.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

Step 4

Include an onload function to your body tag to initialize Facebook javascript (Step 6).

<body onload="initFB();">

Step 5

As you continue to print out the HTML for this page, include a standard Login form, but add somewhere next to it a Facebook Connect login button.

<form method="post" action="loginPost.php">
Username:<input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit'" value="submit">
Or Login with Facebook: <fb:login-button length="long" background="light" size="medium"></fb:login-button>

You can see that this form posts to loginPost.php which should just be your regular login handler (not discussed in this tutorial). If they use the login form, then they are not interested in Facebook connect, so just check their username/password and log them in as usual. They can always choose Facebook connect the next time.

If they do click the Facebook connect login button, then we get some magic. The funny thing about XFBML (which is what this fb:login-button tag is by the way), is that what you put on your page in HTML or print out in PHP is not what ends up on the user's browser. Initially of course the browser just gets the tag as shown, but as soon as the Facebook javascript kicks in (see the init function below) their javascript code will parse the page DOM and add some HTML in between the start and close fb:login-button tags.

In this case it will be a link that will open up a new browser window that looks like a dialog box. If the user is not logged into Facebook at this point the "dialog box" will prompt them to log in. After that, or if they were already logged in to Facebook (but hadn't authorized your site yet) they will be prompted to "Authorize" your site for Facebook Connect.

Step 6

Ok, now similar to what we had on the "Landing Page", we will initialize the Facebook javascript objects here. Except this time, we are doing it a bit differently. Here, instead of using FB_RequireFeatures, we'll just call the FB.init function directly, but pass it a new parameter "reloadIfSessionStateChanged":true .

<script type="text/javascript">
function fbConnect() {
	FB.init("", "xd_receiver.htm",{"reloadIfSessionStateChanged":true});

Well, we have to call FB.init to get the javascript Facebook objects loaded and to render our fb:login-button properly. But the reloadIfSessionStateChanged serves another purpose, which is to reload this page if their "session state" changes. In this case, their "session state" is determined by the Facebook Javascript code and is one of three states:

  1. User is logged into Facebook but has not Authorized your site yet
  2. User is logged in to Facebook and has already authorized your site
  3. User is not logged in to Facebook and thus Facebook doesn't know whether your site has been authorized or not. In fact, they may not even have a Facebook account at this point

My tests show, that the page reload occurs automatically (without user action) if the user is

  1. already logged into Facebook (can be with Facebook permanent cookies) and
  2. has already authorized your site for Connect (but hasn't visited your site yet in this browser session)

This is great, because it gives a seamless Single Sign On experience to the user. When the page does reload, the php code will pick up cookies that get set with Facebook Javascript code (using some cross domain scripting and DOM magic) and it will detect $fb_user and redirect to your Logged in User page.

The page will also reload after the user clicks the fb:login-button if by doing so they use the subsequent dialog boxes to login to Facebook and Authorize your site, or if they've already authorized your site and just use the dialog box to login to Facebook.

Basic idea is: page auto reloads (no user action) if everything is already as connected/authorized as it can be, and page reloads after user clicks fb:login-button, if they do a Facebook login and/or Authorize your site using the dialog boxes that popup.


There really is some magic going on here. Consider that the Facebook Javascript code figures out whether your site is authorized and if the user is logged into Facebook. Then if all is hunky dorry it creates cookies with Facebook data (like their Facebook user_id) as session cookies under YOUR domain. This is pretty key, and the cookies can then be used by PHP code (or other javascript code if you want) to get that user_id and make other calls to Facebook using it.

In some cases Facebook Javascript code will initiate its iFrame within an iFrame approach. I'm not going to delve into details here, but this has some more info , and there is a nice article on Microsoft Developer Network as well that discusses some of this kind of trikery.

Note that your xd_receiver.htm file is involved in this. But from what I've seen (by watching my server logs), Facebook doesn't always make a call to xd_receiver.htm to create the cookies on your domain. Regardless, its pretty cool that it works and is so easy to implement. I suppose it also highlights security issues of puting someone elses javascript code on your site. There is a lot that can be done with it, but I'm choosing to trust Facebook.


Alright, take a breather. Hope all the page reloads and funky Facebook Javascript code didn't make you woozy. Next up is the Connect Account page, which the user gets redirected to if they've authorized your site with Facebook connect, but your code doesn't find their Facebook user id in your database.