Why reading this tutorial

  • You DON’T have a Registration System and you want to implement one in your website
  • You don’t want to start from scratch
  • You want to use Facebook Registration Plugin (obviously)!

Please note that this tutorial will cover the first case of the User Registration Flows document (My site only uses Facebook for Registration).

Back to top

Understanding the plugin

I really recommend you read the Plugin document before start reading this tutorial as we are not going to cite it all back here. Now after reading the documentation we will be:

  • Setting the fb_only attribute:

    Optional. (boolean) Only allow users to register by linking their Facebook profile. Use this if you do not have your own registration system. Default: false.

  • Using the “Login + Registration Flows” approach
  • Using the PHP-SDK to read the signed_request instead of writing the function ourselves
  • Verifying the fields attribute as advised by Facebook in the Registration Advanced Uses document:

    To protect yourself against this attack, you should look inside the registration_metadata key and make sure the fields exactly match the fields you used to build your forms.

So basically, on our main page we will have the Login button with the registration-url attribute:

	registration-url="<?php echo $config["base_url"]; ?>register.php" />

pointing to our registration page.

If the user is not registered the Login button will change to Register:

Facebook Registration Plugin Main PageOur main page

To better understand this tutorial, download the project and browse the code while reading.

Back to top

Creating the registration page

We have the following points in our registration page to consider:

  • The registration plugin:
    	fields='<?php echo retrieve_fields($config["fb_fields"]); ?>'
    	redirect-uri="<?php echo $config["base_url"]; ?>"
  • The functions that is retrieving the fields attribute <?php echo retrieve_fields($config["fb_fields"]); ?> where the $config["fb_fields"] looks like:
    $config["fb_fields"] = array(
        array("name" => "name"),
        array("name" => "email"),
        array("name" => "location"),
        array("name" => "gender"),
        array("name" => "birthday")

    Here retrieve_fields() is only returning the fields json encoded. Also please note that the database table structure will reflect the above fields and you are free to change the fields array and the database table structure to your liking.

  • We add a small Javascript snippet to prevent accessing the registration page if not necessary:
    FB.getLoginStatus(function(response) {
    	if (response.status == "connected" || response.status == "unknown") {
    		window.location = "<?php echo $config["base_url"]; ?>";

    Remember the user only allowed to access this page if he is logged-in to Facebook and not already registered (a.k.a notConnected)

  • The redirect-uri="<?php echo $config["base_url"]; ?>" is pointing to our main page, so we need to remember capturing the $_REQUEST variable there and process it to complete the registration process

And here is the full code:

<?php require 'functions.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>How To:Use Facebook Registration Plugin As Your Registration System</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />

<div id="wrapper">
    <div id="header">
        <div class="head-title"><h1><a href="#">How To:Use Facebook Registration Plugin As Your Registration System</a></h1></div>
    <div id="content">
        <div class="reg-cont">
            <div id="fb-root"></div>
            <script type="text/javascript">
                window.fbAsyncInit = function() {
                        appId   : '<?php echo $config["fb_app_id"]; ?>',
                        status  : true,
                        cookie  : true,
                        xfbml   : true
                    FB.getLoginStatus(function(response) {
                        if (response.status == "connected" || response.status == "unknown") {
                            window.location = "<?php echo $config["base_url"]; ?>";
                (function() {
                    var e = document.createElement('script');
                    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
                    e.async = true;
                fields='<?php echo retrieve_fields($config["fb_fields"]); ?>'
                redirect-uri="<?php echo $config["base_url"]; ?>"
Back to top

Preparing the database

Depending on your preferences ($config["fb_fields"]) and what you want to retrieve from the Facebook user, you may need to change the table structure:

CREATE TABLE `db_name`.`users` (
	`fb_id` VARCHAR(25) NOT NULL,
	`name` VARCHAR(255) NOT NULL,
	`email` VARCHAR(255) NOT NULL,
	`gender` ENUM('male','female') NOT NULL,
	`birthday` DATE NOT NULL,
	`location` VARCHAR(255) NOT NULL,
	PRIMARY KEY (`id`), UNIQUE (`fb_id`)
) ENGINE = InnoDB;
Back to top

Creating the main page

Here are the key points:

  • First things first, we need to check if we’ve been called from the register.php page and complete the registration process (by calling check_registration($facebook,$config["fb_fields"]);)
  • Verify the fields attribute, as mentioned earlier (by calling verify_fields($response["registration_metadata"]["fields"], $fb_fields);)
  • And if all good, register_user($response);!

The above is described (code-wise) below:

function verify_fields($f,$sf) {
    $fields = json_encode($sf);
    return (strcmp($fields,$f) === 0);

function register_user($resp) {
    extract($resp["registration"],EXTR_PREFIX_ALL, "fb");

    // prepare values
    $fb_id = mysql_real_escape_string($resp["user_id"]);
    $fb_birthday = date("Y-m-d" , strtotime($fb_birthday));
    $fb_name = mysql_real_escape_string($fb_name);
    $fb_location = mysql_real_escape_string($fb_location["name"]);

    $query_str = "INSERT INTO users VALUES (NULL, '$fb_id', '$fb_name', '$fb_email', '$fb_gender', '$fb_birthday', '$fb_location') ON DUPLICATE KEY UPDATE fb_id=fb_id";

function check_registration($fb, $fb_fields) {
    if ($_REQUEST) {
        $response = $fb->getSignedRequest();
        if ($response && isset($response["registration_metadata"]["fields"])) {
            $verified = verify_fields($response["registration_metadata"]["fields"], $fb_fields);

            if (!$verified) { // fields don't match!
                header("location: bad.php");
            } else { // we verifieds the fields, insert the Data to the DB
                $GLOBALS['congratulations'] = TRUE;

So the steps again are:

  1. If we have a $_REQUEST check and parse the signed_request using the PHP-SDK
  2. If we got the registration_metadata object, check it against our fields
  3. If everything is fine…then register the user!

Main page after successful registrationWelcome message after successful registration

Now the above will only apply if it was redirected from the registration page. But if the user is already logged-in to facebook and registered (have a valid session), he will simply see a “welcome back” message:

UPDATE: This code uses the old PHP-SDK (v2.x). While the new PHP-SDK may work; once the JS-SDK is upgraded by Facebook this tutorial will be updated accordingly. (reference)

if ($session) {
    try {
        $uid = $facebook->getUser();
        // We can use a Graph API call from the PHP-SDK
        //$me = $facebook->api('/me');
        // Or just use our Database!
        $me = get_user_by_id($uid);
    } catch (FacebookApiException $e) {

Welcome back messageWelcome back message for already registered member

Back to top

Final notes

  • This tutorial can be built and tested locally on your machine, read our “How To: Develop Your Facebook Application Locally” tutorial for more information.
  • The user will stay logged in as long as he’s logged in to his Facebook account
  • This tutorial is just meant to introduce the Facebook Registration Plugin and it’s an initial implementation. It’s not recommended to use it on live websites (especially large scale websites/projects)
  • A full tutorial on how to integrate the Facebook Registration Plugin besides your registration system will be available soon, so stay tuned!

And finally, the project is available for download:

Registration Plugin Sample (5216)

Back to top
  • http://ecodino.com Brandon Hall

    Thanks! Great tutorial!

    • http://www.masteringapi.com Ibrahim Faour

      You are welcome!

      • Daniel Spartus

        hey dude……. im adding the fb registration plugin to my site …….. 1.how do i know the no of ppl the hv regested …..2. how do i get there email and passwords……etc…
        im new to the registration process so can u help me…..u can make a totorail……….

        • http://www.masteringapi.com Ibrahim Faour

          1) By saving the form details to the DB!
          2)The email is already there, but what do you mean by passwords? their Facebook passwords?!! Facebook will NOT allow this!!

          As for helping you, I guess the tutorial is clear enough. If you need more help, you can always hire us (Contact page)!

  • http://profiles.google.com/andrewjshults Andrew Shults

    Nice write up! Few little things about the database scheme (especially targeting MySQL):
    1) Facebook uses 64-bit integers for user IDs – if you use a standard INT (32-bit signed) a large number of the IDs are going to get truncated down to 2^31-1. There are two solutions: use an unsigned BIGINT (64-bit), or use a VARCHAR(20) to store the ID. Personally, I would recommend the VARCHAR since PHP doesn’t support 64-bit integers unless you compile it yourself with 64-bit support (which is fairly uncommon so you may run into other issues).
    2) The max length of a VARCHAR is 255 characters, anything longer is going to get truncated (silently in the case of MySQL).

    • http://www.masteringapi.com Ibrahim Faour

      Great addition! Thanks mate. I do use BIGINT in other tutorials, I just don’t remember why using INT here, I guess it’s the late night article writing 🙂

      I really don’t think it’s necessary (yet) to use VARCHAR for this purpose. Anyway, you gave me a good “night research” material!

  • Fridayanab Baabullah

    how to unregister user from my site…?
    thank you

    • http://www.masteringapi.com Ibrahim Faour

      Un-registering a user would be by removing the App, which can be done by the old auth.revokeAuthorization method. Please note that some work from your end might be needed.

  • Simon

    thanks for this!
    but why is it’s not recommended to use it on live websites?

    • http://www.masteringapi.com Ibrahim Faour

      Because I haven’t done any extensive testing for it. It just meant to demonstrate and give an introduction to the plugin. Anyway, what I meant of the above is “Use at your own risk” 🙂

  • http://www.facebook.com/profile.php?id=222702241 Greg Hesp

    Im trying to port this as a WordPress theme however I am having no luck. Its as if WordPress is blocking any of the Facebook connectivity stuff.

    I’ve uploaded both versions here if anyone can help?


  • http://www.facebook.com/profile.php?id=100001480542168 Jose Antonio

    excelente tutorial, estaba buscando un ejemplo asi 

  • http://www.mundodelamor.com/ MdAmor

    I am having a problem with this. Can you help?
    I am trying to use the login button with the reg-url.
    Without the reg-url, upon login will request permissions, but when I add the reg-url upon login the user is redirected to the url without a  permissions request.
    I need the perms to fill in the reg form.  How do I get them?

    • http://www.masteringapi.com Ibrahim Faour

      This is a missing feature in the registration plugin, please vote for this ticket to make it done!

  • Jamesbonline

    Hi Ibrahim, great post thanks for sharing.

    I have a question about the ‘register’ button associated with this registration form. If I put this on my site I would like it to say Sign Up. Is this possible, or is this button not accessible by us.


  • Jfbooking

    Geez  I got a Call to undefined method Facebook::getSession() in

    • Jfbooking

      line 14 which is ..    $session = $facebook->getSession(); any idea why?

      • http://www.masteringapi.com Ibrahim Faour

        Obviously you are using the New PHP SDK. Please read the updated (before the final notes). Our example will be updated once the new JS SDK is released (hopefully in 12 days).

        • Thales

          Ibrahim Faour MOD • a year ago •….
          (hopefully in 12 days).

  • http://blog.omarxp.web.id Emailsayadi

    thanks, I’m looking for articles like this, really helped me.

  • Maulik Patel

    i am download the this project… but in index.php file the error like this…
    Fatal error: Call to undefined method Facebook::getSession() in /home/technoho/public_html/paymenttesting/facebook-php/app_name/index.php on line 14
    $session = $facebook->getSession();

    • http://www.masteringapi.com Ibrahim Faour

      It seems that you are using the latest SDK while our code uses the old SDK. Please read the note left above. We will be updating the project once the new JS-SDK is released (it should be any time soon).

      • Sasa Marinic

        Hi Ibrahim, many thanks for this amazing piece of work. is there an update for JS-SDK?

  • Svenrue

    Hey, i really like this tutorial but i’d love to see the Tutorial for  the Facebook registration beside my already build up registration system. You said that it will be available soon (in February).
    So where is it 🙂

  • http://www.facebook.com/profile.php?id=833622575 Amal Prasad

    how do i add other fields during registration? like employer, relationship status, username, etc..

  • Kevinkavs

    we’ll ur the best

  • http://www.tickity.com Gary J

    thanks for the great article.  we’ve implemented the registration plugin on Tickity (www.tickity.com) and so far been pleased with the results.

    • Sasa Marinic

      Hi Gary, tickity looks ver good. You have done a good job. Would you mind sharing the piece of script incorporating the passwords in php? thanks,


  • http://jagoster.com/domain.html Domain Murah

    nice, thanks for the article, I save this page.

  • Jimi

    Really need an update to this post PLEASE. This code WILL NOT work from the 1st October onwards!

  • Greg

    Ibrahim,Thank you for the tutorial.  I’ve got the entire thing coded up and almost working.  But the  following PHP line results in one of two results:

    <fb:login-button registration-url="register.php” />

    The first result is that on some end-users’ browsers the user is presented with a Login button.


    Other users are presented with a Register button.

    Compounding the problem, the behavior is different between the two.  If the end user is presented with the Register button then upon a button press the user is immediately taken to the
    $config[“base_url”]; ?>register.php”

    page on my website.  Once there I’m not quite sure exactly what I’m supposed to do with them on that page.

    If the user is presented the Login button then upon pressing the button FB opens a dialog box with normal FB login type entry boxes presented.  Upon entering their credentials and pressing the OK (yes, proceed, etc….) button then they are correctly taken back to the originating page, the originating page is refreshed and they are correctly shown as logged into the system.  This is great, it works exactly like I would want it to work.

    Thus, per my problem, I have a page called user_manage.php which in my problematic case presents the user with a FB Register button.   That Register button takes the user to register.php.  I understand all of that.  What should be presented on the register.php page and what step(s) should be taken to have them automatically taken back to the original page I’m calling user_manage.php?

    BTW, Any update of the Registration material you presented here would be greatly appreciated.



  • Phive57

    Hi, Do you have the update of you tutorial ?

  • Anonymous

    any update for new JS-SDK?

  • http://baturajaonline.com/ bhenk

    I am going to try it soon. Thanks for the tuts bro..

  • Anonymous

    This is not working now…Since facebook has updated the php sdk…!:(

  • Ait Mizul

    hi, so, how to retrieve the data to the database?
    whats the use of creating the db table?

    sorry if its a noob question. i’m new 🙂

  • Ohood Kishawe

    hi, thanx for the tutorial, but i used it and didn’t succeed to reach the logged in status,  i think its because of the newfb sdk, can u please attach a full working project, i need it baaaedly

  • DhimanSaha

    Great article!

  • swati

    hi , thanks i am looking for artical like  this

  • Sonalmac

    What is ../src/facebook.php in index.php?

  • http://www.facebook.com/profile.php?id=674805357 Phil Simmonds

    Great tutorial! I was just wondering, how would you add custom fields and their descriptions to the include file?  I am trying to add address details, first and last names but it’s telling me to add a description and type to the fields, any ideas?

  • http://www.facebook.com/profile.php?id=671951458 Ivan Ruiz

    What about the unsuscribe Option ? or Unregister ?

  • sweetmaanu

    tutorial out dated

    please modify or update tutorial.

  • Bhanu

    Hi.. Can somebody tell me that from where i can get ../src/facebook.php.I am not finding any src folder in the download.

  • http://www.facebook.com/aquadslife Brian D. Parker

    The fix is this in the index.php file:

    getSession(); but replace this with what you see below
    $user = $facebook->getUser();

    //this stays as $me bellow
    $me = null;

    // Session based API call.
    // This was if ($session) { but just replace it with if ($user) { and it should work properly.
    // Awesome ARTICLE BTW!

    if ($user) {
    try {
    $uid = $facebook->getUser();
    // We can use a Graph API call from the PHP-SDK
    //$me = $facebook->api(‘/me’);
    // Or just use our Database!
    $me = get_user_by_id($uid);
    } catch (FacebookApiException $e) {

  • meldina’z 12