Facebook is a social network which allows friends and family to connect and communicate. Facebook has also become a massive social platform which can be used to authenticate users to other websites, and provide user information via it’s Graph API.

Use a Frame-Busting Redirect To Authorize Facebook Applications

Here’s a trick I picked up during development of my new Facebook application, My Wishlist. I picked this one up at Stack Overflow.

When you begin developing for Facebook, one of the first trick’s that you’ll learn is how to check for a Facebook session and how to redirect the user to the Facebook login page if they aren’t logged in or haven’t authorized your application.  Usually that code looks something like this:

<?php
$fb = new Facebook(array(
    'appId' =&gt; 'XXXXXXXXXXXXXXXXX',
    'secret' =&gt; 'XXXXXXXXXXXXXXXXXXX',
    'cookie' =&gt; true
));
 
$session = $fb-&gt;getSession();
 
if($session)
{
    // TODO Show your application's canvas.
}
else
{
    // Redirect the user:
    header('Location: ' . $fb-&gt;getLoginUrl(array(
        'next'   =&gt; $_SERVER['PHP_SELF'],
        'canvas' =&gt; 1,
        'display' =&gt; 'page'
    )));
}

If you’re developing an Iframe-based Facebook application (soon to be the only option since FBML has been deprecated), you’ve got a real problem: The redirect will happen within your application’s IFrame, with the actual login page content hidden within the frame. You’ll recognize the problem because it will look a little something like this:

This is what happens when you redirect to the login page within a Canvas-based Facebook application.

This is what happens when you redirect to the login page within a Canvas-based Facebook application.

The solution to this problem is to use what I call a Frame-Busting Redirect using JavaScript:

<?php
$fb = new Facebook(array(
    'appId' =&gt; 'XXXXXXXXXXXXXXXXX',
    'secret' =&gt; 'XXXXXXXXXXXXXXXXXXX',
    'cookie' =&gt; true
));
 
$session = $fb-&gt;getSession();
 
if($session)
{
    // TODO Show your application's canvas.
}
else
{
    // Redirect the user:
    echo "<script>\n";
    printf("top.location.href= \"%s\";\n", $_SERVER['PHP_SELF']);
    echo '</script>';
}