Pre Fill A Form With Users Facebook Data

🦖 This post was published in 2011 and is most likely outdated.

This is a step-by-step tutorial for allowing you to pre-fill a form on your website with user’s Facebook data such as his email, name, address, etc.

In order to get the user’s Facebook data, the user has to be logged in your website with his Facebook account.

You need your Facebook app credentials (App ID and App Secret). If you don’t have a Facebook app registered or you don’t know what that means, go to facebook.com/developers (I assume you already have a Facebook account) and click on “Set Up New App” and follow the wizard.

Important: make sure you filled “Site URL” and “Site Domain” with your infos. You are given an App ID and an App Secret that we will be using in step 2.

Facebook API call

We are using the Facebook PHP SDK (see on github) to deal with authentication and make API calls.

require "facebook.php";

$facebook = new Facebook(array(
    'appId'  => '...',
    'secret' => '...',
));

$user = $facebook->getUser();

if ($user) {
  try {
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    $user = null;
  }
}

The form

<?php if ($user): ?>
    <form action="#" method="get">
        <input type="text" name="name"
            value="<?php echo $user_profile['name'] ?>">
        <input type="submit" value="Continue &rarr;">
    </form>
    <a href="<?php echo $facebook->getLogoutUrl() ?>">
        Logout of Facebook
    </a>
<?php else: ?>
    <a href="<?php echo $facebook->getLoginUrl() ?>">
        Login with Facebook
    </a>
<?php endif ?>

I wrote this page after an answer I made on Stackoverflow.

Comments