TIGblogs TIG | TIGblogs GROUP TIGBLOGS LOGIN SIGNUP
Vidicorp Blog
Vidicorp Blog
Implementing Facebook Authentication using PHP

Several benefits exist in adopting decentralized authentication schemes –

reduction in  the number of clicks required for authentication, increased conversion rates and easy user-specific customization of services . This article discusses

how you can log in users to your website using Facebook (decentralized) authentication schemes and the PHP SDK found on the Facebook developers website. To get a

clearer picture, you can read the prequel articles  on Decentralized

Authentication and How Facebook Authentication Works.

  1. Setup a Facebook App Account. Obtain your App id, App secret
  2. Download and extract the Facebook PHP SDK into your php project folder .href="https://github.com/facebook/php-sdk/">https://github.com/facebook/php-sdk/ . It contains 3 folders – examples (containing a brief sample on which this

    tutorial is built), src (contains the main php Facebook class), and tests (test cases).

  3. Create a php file. fbconnect.php to generate the login button and displaythe details of the authenticated user.

FbConnect.php

<?php
// Include the Facebook sdk base file.
require 'fb/src/facebook.php';

// Create our Application instance
$facebook = new Facebook(array(
   'appId'  => '*****Your Appid*********',
  'secret' => '***Your App Secret*******',
));

// Get User ID if user is logged in
$user = $facebook->getUser();

// Given that this page is redirected after user login,
// We should have the required code/permission to request user details

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
	//Request current users details hopefully he allowed the app :)
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }

}

$loginUrl = $facebook->getLoginUrl(
	array(
		'scope'         => 'email',
	)
);
?>
<?php if ($user) {?>
<a href='<?php echo $facebook->getLogoutUrl(); ?>'>Logout</a><br />
<?php } else { ?>
<a href='<?php echo $loginUrl; ?>'><img src='http://vidicorp.org/images/fblogin.png' width='149' height='22' alt='Login With Facebook' /></a><br />

<?php
}
// Display User detials.
if ($user ):
	echo $user_profile['first_name'] . "<br />";
	echo $user_profile['last_name']  . "<br />";
	echo $user_profile['name']  . "<br />";
	echo $user_profile['id']  . "<br />";

	echo "<br /><br /> Full User Profile <br />" ;
	print_r($user_profile) ;
	echo "<br /><br />Available Permission <br />" ;
	$user_permissions = $facebook->api('/me/permissions');
	print_r($user_permissions) ;
	echo "<br /><br />User Notes (if shared) <br />" ;
	$user_permissions = $facebook->api('/me/notes');
	print_r($user_permissions) ;
    // Set up User session and redirect to appropriate home page ;
    //$logoutGoTo = "/profilespage";
    //header("Location: $logoutGoTo");
    //exit;
else:
  // If user is not logged in, print out error message
  if(isset($_REQUEST['error'])) {
	if ( $_REQUEST['error_reason'] == 'user_denied') {
		echo "<br />Oops! You have declined to login using Facebook. ";
	}else {
		echo "<br />Oops! Facebook  Error." . $_REQUEST['error_description']  ;
	}
  } else {
	  echo "<br />You are not Logged in" ;
  }
endif
?>

The Facebook PHP SDK simplifies much of the authentication process using simple calls on the main facebook class. First we include the main facebook.php file (found in

the src folder of the downloaded facebook php sdk). Next, we create an application instance using your Appid and App Secret (more about that in previous article)..

remember to enter them correctly.

$facebook = new Facebook(array(
   'appId'  => '**** AppId *************',
  'secret' => '******App Secret***********',
));

A login URL is generated using the getLoginURL() method.

$loginUrl = $facebook->getLoginUrl(
	array(
		'scope'         => 'email',
	)
);

The getLoginURL() method also generates  a state session variable which is checked to counter CSRF attacks. The scope parameter specifies permission request for the

user data you want to access. An optional redirect_uri parameter (not shown above) could also be specified to indicate the page to which the user is redirected after

authentication is completed via facebook. When it is not explicitly specified as above, the user is redirected back to the same page (fbconnect.php). Remember that the

more permissions you request, the less likely users will Allow your app.  Finally, use the generated url as a login link.

<a href='<?php echo $loginUrl; ?>'><img src='http://vidicorp.org/images/fblogin.png' width='149' height='22' alt='Login With Facebook' /></a><br />

The user is redirected to back the same fbconnect.php page after authentication via the facebook OAuth dialog. If authentication has been successful, an authorization

code URL variable should be available now. The api() method simply uses this code (obtained from the URL) to request an access token, verifies correctness of the state

session variable (to guard against CSRF attacks) and calls the facebook graph api in order to receive the users details in return. The method call

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

is equivalent to accessing 

https://graph.facebook.com/me&access_token=**************  

https://graph.facebook.com/users_username

with the appropriate access token.

The result of the api method can then be accessed to obtain user details

echo $user_profile['first_name'] ;

. A logical step in your application after obtaining these details would be to create the user’s record (registration) in your  database using the obtained details and

start a session (login) for the authenticated user.

More information about a user can be obtained by making the api calls e.g
$facebook->api(‘/me/notes’); — Users Notes
$facebook->api(‘/me/friends’); — Users Friends
$facebook->api(‘/me/permissions’); — Users Available Permissions

Full list of available information via the graph api can be found here .
NOTE : You need to explicitly get the users permission in order to view their detail. E.g you should add user_notes to your scope

scope => email,user_notes,

parameter in order to successfully obtain the user’s email and notes information via the graph api. It may be available without requesting permissions only if the user

shares this information with everyone under his/her privacy settings.
Full list of permissions can be found here 

Download the Facebook login button image.
Download fbconnect.php here .

A live demo can also be found here. .

 

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Facebook Post to StumbleUpon


July 6, 2011 | 10:07 AM Comments  0 comments

Tags:
You must be logged in to add tags.


Vykthur's Profile

Vykthur's Friends


Latest Posts
Implementing Facebook...
Implementing Facebook...
How Facebook...
Facebook...
Decentralized...

Monthly Archive
July 2007
May 2010
September 2010
October 2010
November 2010
July 2011

Change Language


Tags Archive
opportunity personaldevelopment thirdworld youth

Filter By Type
Topics

Friends
'Yemisi
Adeshola
Cat
cheta
Chloe
Enigma
Enigma
Enigma
Enigma
Eta Eta Uso
Henry Ekwuruke
JayBruce
Maricarmen
nadia
Sara Donají
sarah
siddiqua
Simon
Timothy Ogene
Yaz


18008 views
Important Disclaimer