XMPP JavaScript Library READ MORE

Authenticating User using Facebook connect

UnCategorised, Sachin Puri, 2011-02-03 22:22:36

Step 1: Create an application on Facebook
Step 2: Write code

Before writing the code you must download Facebook PHP client library

Including facebook class in your code

require_once '../sdk/src/facebook.php';

Initialize the variables

$app_id='<Your application ID>';
$secret='<Your application secret ID>';

Create an object of facebook class

$facebook = new Facebook(array(
  'appId' => $app_id,
  'secret' => $secret,
  'cookie' => true,

Get the url of Login and Logout pages

There are two function:
getLoginUrl() which return full URL for facebook Login page.
getLogoutUrl() which return full URL for facebook Logout page.

$fb_login_url = $facebook->getLoginUrl($params);
$fb_logout_url = $facebook->getLogoutUrl();

Get the active session


Check whether session exists or not if session exists then then

    #Session exists, Now get User ID and other information
    #Session does not exists, Now redirect the user to facebook Login page
    echo "<script>top.location.href='$fb_login_url'</script>";

Access user data

    $userid = $facebook->getUser(); 
    $userdata = $facebook->api('/me'); 
}catch(FacebookApiException $e){}

Check whether data fetched or not


    #If user data is available then fetch the data from $userdata   
    #If user data is not available then Provide a link for Facebook Login page
    echo "<a href='$fb_login_url' target='_blank'><img src='http://www.sachinpuri.com/facebook/authenticate_user_with_facebook_connect/img/fbconnect.gif' border='0'/></a>";


Fetching user data from array  returned by $facebook->api('/me');   api call

Here we will fetch the required data from array returned by $facebook->api(‘/me’) api call. In below example we are fetching data and passing it to a form and then we can write the code to save this data in our database.

#If user data is available then fetch the data from $userdata
$user_name= $userdata['name']       

<a href='<?=$fb_logout_url?>' class='fblink'>Logout</a>
<form name='frm1'>
<input type="text" name="name" value="<?=$user_name?>"/>
<input type="text" name="email" value="<?=$email?>"/>
<input type="button" name="submit" value="submit" onClick="send_data_to_parent()"/>


See it in Action

Download Code
Add Your Comment
    Yes! I want to receive all comments by email

No Comments Posted Yet. Be the first one to post comment