Authenticate Users With Their Facebook Account

A good and easy way to deal with Facebook authentication is to implement the server side flow with the Facebook PHP SDK (see on github). Here is how you do that :

require "facebook.php";
$facebook = new Facebook(array(
    'appId'  => YOUR_APP_ID,
    'secret' => YOUR_APP_SECRET,
));

$user = $facebook->getUser();

if ($user) {
  // The user is logged in
  try {
    $user_profile = $facebook->api('/me');
    // Here : API call succeeded,
    // you have a valid access token
  } catch (FacebookApiException $e) {
    // Here : API call failed,
    // you don't have a valid access token
    // you have to send him to $facebook->getLoginUrl()
    $user = null;
  }
} // else : the user is not logged in

After that, if $user is not null, it means that the user is authenticated. So here is what you can display on your page :

<?php if ($user): ?>
    <a href="<?php echo $facebook->getLogoutUrl() ?>">
        Logout of Facebook
    </a>
<?php else: ?>
    <a href="<?php echo $facebook->getLoginUrl() ?>">
       Login with Facebook
    </a>
<?php endif ?>

When the user is authenticated, you can make API calls with his access token (stored in $facebook) :

$user_profile = $facebook->api('/me');

For the complete flow, you can see the example of the Facebook PHP SDK which is well documented.

Quentin Pleplé
June 2011