How To: Use Facebook Registration Plugin As Your Registration System
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)!
Back to topPlease note that this tutorial will cover the first case of the User Registration Flows document (My site only uses Facebook for Registration).
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_onlyattribute: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_requestinstead of writing the function ourselves - Verifying the
fieldsattribute 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:
<fb:login-button 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:
Back to topTo better understand this tutorial, download the project and browse the code while reading.
Creating the registration page
We have the following points in our registration page to consider:
- The registration plugin:
<fb:registration fields='<?php echo retrieve_fields($config["fb_fields"]); ?>' redirect-uri="<?php echo $config["base_url"]; ?>" fb_only="true" width="530"> </fb:registration>
- The functions that is retrieving the
fieldsattribute<?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 thefieldsarray 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$_REQUESTvariable 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">
<head>
<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" />
</head>
<body>
<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>
<div id="content">
<div class="reg-cont">
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
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;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<fb:registration
fields='<?php echo retrieve_fields($config["fb_fields"]); ?>'
redirect-uri="<?php echo $config["base_url"]; ?>"
fb_only="true"
width="530">
</fb:registration>
</div>
</div>
</div>
</body>
</html>
Back to topPreparing 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` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`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 topCreating the main page
Here are the key points:
- First things first, we need to check if we’ve been called from the
register.phppage and complete the registration process (by callingcheck_registration($facebook,$config["fb_fields"]);) - Verify the
fieldsattribute, as mentioned earlier (by callingverify_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";
mysql_query($query_str);
}
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;
register_user($response);
}
}
}
}
So the steps again are:
- If we have a
$_REQUESTcheck and parse thesigned_requestusing the PHP-SDK - If we got the
registration_metadataobject, check it against ourfields - If everything is fine…then register the user!
Welcome 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) {
error_log($e);
}
}
Welcome back message for already registered member
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 (4320)
Back to top- http://ecodino.com Brandon Hall
- http://www.masteringapi.com Ibrahim Faour
- Daniel Spartus
- http://www.masteringapi.com Ibrahim Faour
- http://profiles.google.com/andrewjshults Andrew Shults
- http://www.masteringapi.com Ibrahim Faour
- Fridayanab Baabullah
- http://www.masteringapi.com Ibrahim Faour
- Simon
- http://www.masteringapi.com Ibrahim Faour
- http://www.facebook.com/profile.php?id=222702241 Greg Hesp
- http://www.facebook.com/profile.php?id=100001480542168 Jose Antonio
- http://www.mundodelamor.com/ MdAmor
- http://www.masteringapi.com Ibrahim Faour
- Jamesbonline
- Jfbooking
- Jfbooking
- http://www.masteringapi.com Ibrahim Faour
- Thales
- http://blog.omarxp.web.id Emailsayadi
- Maulik Patel
- http://www.masteringapi.com Ibrahim Faour
- Sasa Marinic
- Svenrue
- http://www.facebook.com/profile.php?id=833622575 Amal Prasad
- Kevinkavs
- http://www.tickity.com Gary J
- Sasa Marinic
- http://jagoster.com/domain.html Domain Murah
- Jimi
- Greg
- Phive57
- Anonymous
- http://baturajaonline.com/ bhenk
- Anonymous
- Ait Mizul
- Ohood Kishawe
- DhimanSaha
- swati
- Sonalmac
- Sonalmac
- FakkU
- http://www.facebook.com/profile.php?id=674805357 Phil Simmonds
- http://www.facebook.com/profile.php?id=671951458 Ivan Ruiz
- sweetmaanu
- Bhanu
- http://www.facebook.com/aquadslife Brian D. Parker
Advertisment
Recent Tutorials
- How To: Create A User Photo Albums Browser Using Facebook Graph API
- How To: Upload A Photo To A User’s Profile Using Facebook Graph API
- How To: Check Status And RSVP To Facebook Events Using Graph API & FQL
- Facebook Javascript SDK Best Practices
- How To: Create Facebook Events Using Graph API – Advanced







