Sunday, April 17, 2011

Facebook login - FConnect Graph API (PHP)


In this post I will be discussing about Graph API. The most basic use of it is when you want the users to register in your website via their Facebook profile. The advantage of doing that is, it saves all the email authentication, captcha etc validations. It simply fetches the users existing details from what is there in Facebook for that user. The use of Graph API is imense, which I hope to cover in my future post. In this I will be just concentrating on letting the users register in a website using the Graph API.

First and the most important thing, is to create your own App in Facebook. This is a very straight forward process, You just need to enter the App name, and URL. An App can be considered as the gateway between your website and Facebook's data. Follow this link to create a new App. Once you have set up your website you will be given a App ID and secret key. This will be needed in your code. So preserve this information carefully.

Now coming to the code. First click here to download the code. The main aspect of this code is the facebook.php file. This is the PHP SDK for Facebook Graph.


First you need to initialise the Facebook object by the App ID and secret key which you got in the above steps by:

$facebook = new Facebook(array('appId'  => 'YOUR_API_KEY','secret' => 'YOUR_SECRET_KEY','cookie' => true,));

When you are initializing the $facebook object, you need to keep in mind what user data access permissions you want to give to the application. In src/facebook.php you will find that in getLoginUrl(). The parameter name is, "req_perms". For more details on permissions, click here.

Now we have to check whether the user has an active session and is registered to the site or not. This is done by the following:

$session = $facebook->getSession();  // getting the facebook session details of the user
$me = null;
if ($session) {
  try {
    $uid = $facebook->getUser();  // retrieving the facebook user ID
    $me = $facebook->api('/me');  // retrieving the user details
  } catch (FacebookApiException $e) {

Now we need to get the predefined login and logout URL's by the following:

if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();

Now we can perform our checking by:

<?php if ($me): 
                      //  code to check whether the user is registered or not. If not it will add the user details returned by Facebook to database.
else: ?>
  You are currently not logged in. Click <a href="<?php echo $loginUrl; ?>">here</a> to login using facebook connect.
<?php endif; ?>

In the above $me array hold the details of the users, who is logging in. If it is empty, that means the user has not logged in thus a login link is provided to the user, i.e. $loginUrl.

Finally if the session is found we perform the following to register the user in our website:

<h1>User Details</h1>
mysql_connect("localhost","root");  // connecting to the database
mysql_select_db("test");  // selecting the DB
if(!mysql_fetch_array(mysql_query("select id from fb_registered_user where email='".$me['email']."'"))){
$q="insert into fb_registered_user set first_name='".$me['first_name']."', last_name='".$me['last_name']."',email='".$me['email']."',dt=curdate(), password='".generateString()."'";
echo '<div style="color:green">User has been successfully registered.</div>';

<td valign="top">
<img src="<?php echo $me['username']; ?>/picture">
<td valign="top">
<b>Name:</b> <?php echo $me['first_name']." ".$me['last_name']; ?><br/>
<b>Email:</b> <?php echo $me['email']; ?>

In the above code, I am first checking whether the email address has already been registered or not by:

f(!mysql_fetch_array(mysql_query("select id from fb_registered_user where email='".$me['email']."'"))){


If not then we are writing the database insert command. In this I am just inserting the username, first name, last name, date and email address from Facebook to my database. But you can add more fields to it as needed. For better understanding, you can print the $me array to see what are the exact data that can be fetched.

Now after the database transaction is done, my job is almost done. Finally I just put a "logout" link, which will log out the user from Facebook itself. We have already got this logout URL before.


For more explanation and customizations contact me at


  1. Nice Article , But i getting error, when i am login to account "an error occurred. please try again later. facebook login"

    Please help me what is the problem.


  2. why i'm getting null for $facebook->getSession(); even if the FB account is logged in? please suggest a fix for this.