Tutorial: Integrate Database Based Facebook Connect To Your Website

Now-a-days it has become a very common norm to allow visitors on your site to connect with their facebook credentials using the “Connect with Facebook” or “Login with Facebook” button. Facebook connect allows users to provide the websites permissions to access their information like the gender, email id, birthdates, etc. There are websites that also take permission to read the whole news feed of the user and also to publish status updates on the users walls. Facebook Connect has been around from 2008. In this post we are publishing the Tutorial to Integrate Database Based Facebook Connect To Your Website

Facebook has released various SDK’s(Software Development Kit) like Javascript SDK, PHP SDK and also SDK for Android and iOS. Since their release there have already been various versions of them that have also released. facebook keeps on changing a lot of its configurations and how Facebook Connect works. There are many tutorials on Facebook Connect around the web. But the problem is that many are outdated, some files have errors while some do not provide the functionality that website owners need. I had a client requirement to integrate Facebook to his existing site. I needed a functionality to store the users facebook data like his name, email, gender, etc. into the clients website database. While working on that project I came to know about the shortcomings of a lot of tutorials on the web. Thus, I thought of creating an article on the bases where the “Connect with facebook” should work also integration with the database has to be there.

In this tutorial you would learn how to

  • Create a Facebook App
  • Get Login/Logout URL
  • Ask for various permissions
  • Use Facebooks API function
  • Access the users facebook data like email id, gender, birthdate, bio, etc.
  • Store the users facebook data into our own database
  • Maintain the users data with Session Management
  • Log the user out of our website, while he/she still being logged into facebook

In this post we are publishing Tutorial to Integrate Database We would be using the PHP SDK to connect the user for this tutorial

Step 1

Download the PHP SDK from the GitHub You would only need the src folder for this SDK. If you want you could discard the other files. After downloading the SDK you need to create the table to store all the data of the users that use your “Connect With Facebook” on your site. In this example I am using the fields ID, Name, Email, Gender, Bio and whether the user has registered from facebook

CREATE TABLE `newmember` ( 
`id` BIGINT( 20 ) UNSIGNED NOT NULL AUTO_INCREMENT , 
`name` VARCHAR( 255 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL , 
`email` VARCHAR( 255 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL , 
`gender` VARCHAR( 10 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL , 
`bio` TEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci , 
`face` VARCHAR( 10 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL , 
PRIMARY KEY ( `id` ) 
) 

Step 2

The second step is to create your application on Facebook. This is done to get the App ID and the App Secret. So, first go to http://developers.facebook.com/apps You might encounter a window where the developer app is requesting your permission to access some of your basic information.

facebook-developer-permissions

Step 3

Now, on the top right hand side click on “Create New App”.

facebook-create-new-app

Now a window similar to the below one would pop up. Here you need to enter the name that you want your App to be named. I always tend to add my blog name as prefix or suffix to my Apps. You could also enter the namespace, it is optional.

facebook-app-details

Step 4

Here you need to add the details about your app. Here, enter the domain name, email address, category of the app. Then you need to mention how you are going to integrate your App with facebook with website, or if your App is on facebook, or for mobile. We need to click on Website. Here we need to add the URL where we are going to allow the “Connect With Facebook”. In my case it is http://artatm.com/demo/flogin Now click on “Save Changes”. On saving you would see the App ID and the App Secret on the top. Save these for further use.

facebook-app-website-details

Step 5

We will first create the main connect file. Create a file named ‘fbconnect.php’. Now, as we have to save the data of the facebook user into the database and use that data for our application we need to ensure that this file is only accessed when the relevant session variables are not set. All our content in this would be lying between the if parenthesis.
Also we would be defining 3 variables for the App ID, App Secret and the Site URL. Enter you App ID and Secret and enter the URL where this connect script is going to work.

if(!isset($_SESSION['user'])) 
{ 
    $app_id        = "The App ID goes here"; 
    $app_secret    = "The App secret goes here"; 
    $site_url    = "The Site URL goes here"; 

Step 6

Next we need to include the ‘facebook.php’ file which is present in the src folder that we got with the PHP SDK. Then, we are creating an instance of Facebook by supplying the 2 variables, $app_id and $app_secret. Then, to check whether the user is logged into facebook or not we would use the getUser() function. getUser() function returns the user id of the logged in user. If the user is not logged in then the $user variable would contain 0. We would need the access token of the user to move forward with the connection.

include "src/facebook.php"; 
$facebook = new Facebook(array( 
    'appId'        => $app_id, 
    'secret'    => $app_secret, 
    )); 
$user = $facebook->getUser(); 

Step 7

Next, we need to get the login and logout URLs. To get the logout URL you need to call the getLogoutUrl() function. For getting the login URL you need to call the getLoginUrl() function.
You could also define the URL where the user would be redirected after logging in and logging out. With getLoginUrl() function you could specify the specific permissions that you want the user to grant you. These permissions could be specified in the scope variable. Below, I am asking the user for his basic information like about him and email. Also, for learning process I am including the read_stream and publish_stream permissions that would allow our application to read the news feed of the user and also give us the permission to publish something on to his wall.

if($user){ 
    // Get logout URL 
    $logoutUrl = $facebook->getLogoutUrl(); 
}else{ 
    // Get login URL 
    $loginUrl = $facebook->getLoginUrl(array( 
        'scope'            => 'read_stream, publish_stream, user_about_me, email', 
        'redirect_uri'    => $site_url, 
        )); 
} 

Step 8

Now, if the user logged into his facebook account then we need to know whether the user is logged into our application or not, because logging into facebook and logging into our facebook application are two totally different things. We do this by trying to fetch the profile of the user.
To retrieve the profile you need to call the facebook’s ‘api’ function. For this you need to pass the parameter ‘/me’. This would give you the basic information about the user. You could call anything using the api function, for example to get the photos you could pass the parameter ‘/me/photos’, ‘/me/friends’ for the friends list. If you want to request many things at one time calling the ‘api’ function again and again would slow your application so instead you could opt for batch processing with jSON.

if($user){ 

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


On doing a print_r() on the variable $user_profile you would see what all things the array now holds about the user. You could easily use any of this information in your application.

Step 9

Now, as we have connected the users facebook with our application, now we need to check whether the users email id is already present in our database or not. If it is present then we would initiate the session variables directly and if not, we would first insert the details of the user like the name, email id, gender into our database and then initialize the session variables.

First, we need to connect to the database. Then run the specific query and then use the if condition.

  
$con=mysql_connect("Your Host Name","Your User Name","Your Password"); 
if(!$con) 
{ 
    die("Could not connect to MySQL"); 
} 
mysql_select_db("Your Database Name",$con) or die ("could not open database"); 
$name = "'" . $user_profile['name'] . "'"; 
$email = "'" . $user_profile['email'] . "'"; 
$gender = "'" . $user_profile['gender'] . "'"; 
$bio = GetSQLValueString($user_profile['bio'], "text");
$query = sprintf("SELECT * FROM new WHERE email = %s",$email); 
$res = mysql_query($query) or die('Query failed: ' . mysql_error() . "
\n$sql"); if(mysql_num_rows($res) == 0) { $iquery = sprintf("INSERT INTO newmember values('',%s,%s,%s,%s,'yes')",$name,$email,$gender,$bio); $ires = mysql_query($iquery) or die('Query failed: ' . mysql_error() . "
\n$sql"); $_SESSION['user'] = $user_profile['email']; } else { $row = mysql_fetch_array($res); $_SESSION['user'] = $row['email']; }

Step 10

Now we need to create our main page ‘index.php’ This is the page where the “Connect With Facebook” button would appear. This is also the page where the details of the user who just logged with the Facebook would appear. First we need to include the ‘fbconnect.php’ and ‘common.php’ file. If the session has not yet been started then the “Connect” image would appear. If the session has started, then the details of the user would be displayed.

session_start();
include "common.php";
include_once "fbconnect.php";

if (isset($_SESSION['user'])) 
echo 'Logout'; 
else 
echo 'Login'; 
if(!isset($_SESSION['user'])) 
{
	echo 'Connect to your Facebook Account'
} 
else 
{ 
	$email = "'" . $_SESSION['user'] . "'"; 
	$query = sprintf("SELECT * FROM newmember WHERE email = %s",$email); 
	$res = mysql_query($query) or die('Query failed: ' . mysql_error() . "
\n$sql"); $row = mysql_fetch_array($res); echo $row['name']; echo " GENDER : " . $row['gender']; echo " EMAIL : " . $row['email']; }

Step 11

Now, we need to create logout.php file. The logout URL that facebook creates has a small problem. When you use that URL to logout, you not only get logged out of the application but also get logged out of the facebook, which is something we do not want to happen. Thus, I have used a script which will just log the user out of the application and not the facebook. I have done this by clearing all the session variables of facebook Application. For this you need to replace the ‘{Your App ID}’ with your own app ID for the below 3 session variables.

unset($_SESSION['user']); 
unset($_SESSION['fb_{Your App ID}_code']); 
unset($_SESSION['fb_{Your App ID}_access_token']); 
unset($_SESSION['fb_{Your App ID}_user_id']); 
header("Location:index.php"); 
exit;

This should be it. You could view the demo or download this tutorial, create the database and make specific changes as mentioned below and everything should start working!

Changes in the Download Package

After downloading the package you would need to follow some simple steps and change a small bit of code to get it working properly. After downloading

  • Create the Database and the table – “newmember” with the required fields
  • Open common.php and put your Host Name, Username, Password and Database name
  • Open fbconnect.php and put your App ID, App Secert, Site URL
  • Open logout.php and replace {Your_App_ID} with your App ID

This should be it! Making all the above changes would easily get your Facebook Connect working. If there are any doubts do let me know in the comments section. I would try to solve all your issues!

Demo and Download

Do you have any queries?

There are lots of things that you could with this script. You could easily integrate this script into your existing website where the normal register and login modules are present. You would only need to tweak this code slightly. If there is anything that you would want to know let me know in the comments. We would try our best to answer your queries.

A total football nerd, he loves designing to the core and also likes to get his hands on some programming. He is the Co-Founder of ArtAtm. He hails from India. You may want to Follow Him On Twitter

Jitu – who has written posts on Artatm – Creative Art Magazine.


116 Responses to “Tutorial: Integrate Database Based Facebook Connect To Your Website”
  1. tRUStY

    Dear Jitu,
    I have a problem after the app is accepted on facebook, it redirest to me to my site and i have the following link: http://sitename.hu/subfolder/?state=2011775c4135bee03b1308dea8df6c85&code=AQA3a5VtYUmUBpavJsgIFCMtHxSdzbq2qNAKcwMMtYMBTqX4X4ClZMZmV9pkywvgyLiM4MKcrZbDTBYyVCZfEAblngs0iLEpHWdey4_1aJzOCgQ0foO0oiDWFOLR4SB9vrQh0gngwOikVeAXIaSg0RL_cgN_ff1A4PkDrnncbQs-Rkm7YTn6DTNl3UijTxsuYHcvcrQyL3DT4DsipocIo1YP#_=_

    I checked the phpmyadmin and it did not take my user to the datebase.

    Can you help me what is the problem?

    Best regards,
    tRUStY

  2. zain

    jitu i download your code and after apply changes i put it on my website. But the problem us that after cfbconnect button it open the facebook login page and after enter my credentials in it, when it redirected to my website. It does not bring any information and session does not set. It still shows that the login link instead of logout. But the address bar have some query string varibales after redirecting to my website

    • Jitu

      @Zain I tried to emulating the whole scenario that you put forward, but I am not getting any errors and everything is working fine on my side! Could you try again and if unsuccessful let me know your website!

  3. Connor

    I even tried to copy and paste exactly what you did above and it doesnt work. Please I need help!!!

  4. Connor

    Whenever I edit the sql query to add more info into new columns for the database nothing happens and nothing gets written. I used the code that you offered above for the facebook picture. as soon as I take out the %s and the variable in the sprintf fucntion it goes back to working. Why is it that this does not work?

    $iquery = sprintf(“INSERT INTO fb values(”,%s,%s,%s,%s,%s,’yes’)”,$name,$email,$gender,$bio,$facebook_id);

    • Jitu

      @Connor Could you provide me with the code of the variable and the SQL query that you want?

  5. Connor

    What is the db structure for this everything works fine but for some reason nothing gets written in the db

  6. amit

    I implemented this code. after implementation facebook redirecting me on my return url but without response. please help me.

    • Jitu

      @amit Could you give me more insight into your problem? I would need more details to identify the problem!

  7. jack tomz

    can you tell me how to save the user’s facebook id into that database too ?? & thanks alot .

    • Jitu

      @Jack For the users facebook ID you would need to create a new filed in the database and then create another variable and then edit the sql query like below
      $uid = GetSQLValueString($user_profile[‘id’], “text”);
      $iquery = sprintf(“INSERT INTO newmember values(”,%s,%s,%s,%s,%s,’yes’)”,$name,$email,$gender,$bio,$uid);

      Let me know if you need to know anything else!

  8. anand

    hello,
    I have created an app and given some facebook page in redirect_url, now what i want is to redirect it again to mysite/etc/…../… because what i want is to just take user to my facebook page make him “like” my page… once he liked then i want him transfer to my app..

    please help… this is my first facebook app….

    thanks in advance
    anand singh

    • Jitu

      @Anand Why do you want to redirect the user to your “Facebook Page”. Instead you could make him like your page on your website itself! In this way you would be able to handle everything on your own!

  9. Wallace

    Worked perfectly here, I’ll be the first in Brazil (in my style site) to have Facebook Connect, looks and I do not know php programming)

    – Google Translate

  10. Wallace

    Nice Nice Nice, Funcionou perfeitamente aqui, vou ser o primeiro no Brasil (no meu estilo de site)a ter o FAcebook Connect, e olha que eu não sei programar php)
    – Google Teanslate

  11. stoi

    everything worked fine since today…but now when i click login i get redirected to the facebooklogin page and log in via my app…everything fine up to this point. but after login i get redirected to the “start-page” and no data is transferred into my database and no picture is shown and so on.

    now my question anyone else got the problem that everything worked fine since today and now this mistake happens?^^

  12. ronan

    when i click the link in the browser url is says…. /fbLogin/$loginUrl……..:( any ideas anyone

  13. ronan

    Query failed: Query was empty?????????????any ideas?????????

  14. pal

    Hi,
    i tried implemineting the code on my website (m using yahoo web hosting service) but it doesn’t work, data is nt being inserted in the newmember table at all, any suggestion??

    thanks,
    Pal

  15. ashwini

    hi i have immplemented all required but after login facebook i am not able to get any data ..may you pls check

    http://www.ashwinisingh.in/fb_connect

    🙁 🙁 🙁

  16. venkatesh

    session_start();
    unset($_SESSION[‘user’]);
    //unset($_SESSION[‘id’]);
    unset($_SESSION[‘fb_23232323223_code’]);
    unset($_SESSION[‘fb_2323232323_access_token’]);
    unset($_SESSION[‘fb_2323232323232_user_id’]);
    header(“Location:index.php”);
    exit;

    this s not working for me, the page s still logged in , any help??

  17. daniel

    this is the link of my test page.. http://www.caldearte.cl/des/face/
    thanks

  18. daniel

    Hi Jitu, great tutorial !
    I have the same problem of Mverth… “But when I open index.php and I’ll try to click on the connect button. It looks like I been redirected to the same page. So nothing happend..” I reset my secret key too, but nothing happen… return of the same index, i can’t see mi picture and any user content.. db newmember registration don’t work for me.
    please helpme.
    thanks

    • Jitu

      @Deniel You are getting the required permission from facebook when a user clicks on the button. The problem lies somewhere else. Could you do one thing? Try to test the script alone without any Ajax, first just try my code out and then if it works, gradually integrate your Ajax part. In this way we may be able to decipher the problem!

  19. Sachin

    Hello Jitu,
    Very nice tutorial. Work done. Thanks a lot.

  20. Maritza

    Hi Jitu,

    It was very nice to find this tutorial. I was wondering if you have worked anything combining javascript and php facebook SDKs. I am working in a jQuery Mobile-based application that makes extensive use of javascript. I am about to start integrating the app with facebook and the database component, but I found that most of the examples that show “facebook connect” do it either with the Javascript SDK or the JS alone. That is, I haven’t found any example showing how to combine both SDKs. My goal is to implement the connection in javascript, then the php portion for storage and streaming of facebook stories to the user’s friends. Any hints? I don’t think it is feasible for me to develop an index file in php, since I would be missing key features in jQuery Mobile that have an impact in performance.

    • Jitu

      @Maritza Even I have not tried implementing the Javascript SDK yet! I will do that as soon as I get some time off my work and let you know, how to go about this!

  21. Bhuwnesh Joshi

    I Want To Read A Users Friend List and Store All Of Them In The Database , But When I Try to Do This , A PHP Error Occur Showing Stripslash Takes parameter 1 as argument and it is also not stored on the database . Can Please Send Me the way To Do That. Thank you In Advance

    • Jitu

      @Mverh That is exactly what is happening when a visitor clicks on the “Connect To Facebook” button for the first time. It never repeats again as we have got his permission from facebook already!

  22. Mverh

    There is still one question I have.

    How can I make it possible to open the Facebook login/connect inside a small popup, like you see on many other websites?

    Thanks!

    • Jitu

      @Mverh Glad that the tutorial was of help to you! Could you give me any example website where the popup thing is implemented?

  23. Mverh

    Sorry for the last post. After I reset my secret key, it all worked. I dont know why, but thanks so far! Great!

  24. Mverh

    Hello,

    First off al, what a great tut! Thank you so much. And you’re right, there are not many up to data tutorials for facebook integration.

    But there is still one problem I’m dealing with. I filled in all the configurtion settings right. But when I open index.php and I’ll try to click on the connect button. It looks like I been redirected to the same page. So nothing happend..

    I’ll hope you can (or someone else) can help me out.

    Thank you!

  25. Ben

    A small addition: It took me a long time to realise that the ‘logout’ function wasn’t working, simply because I’d mistakenly replaced the app id in logout.php, leaving the curly brackets present (remove the brackets when you paste the numbers in. Avoid this mistake. 🙂 ‘app_{APPIDHERE}_id’

  26. Ben

    Jitu, a great tutorial – thanks.

    I hit two errors (possibly in the new PHP version) in that I had to add ‘echo’ etc to a html space, and also had forgotten to rename the ‘include’ for facebook.php file to fit the path I’d uploaded to. This solved the ‘Facebook’ class not found detailed in your comments. (Thanks to StackOverflow for this).

    Thanks for doing a modern tutorial and getting us started!

  27. Sherrie

    Hi,
    I was wondering do you have a tutorial or know of one that can integrate with facebook and my database. I am trying to create a page which people can post a thought on in my wordpress site but I would like them to have the option to post to my facebook page or their own facebook page which ever is easiest to do.

    thank you for your time,

  28. Christen

    Hey great tutorial…just what i needed 🙂 and very complete as well.

    I have a minor question for you. which might have to due with the fact that im a beginner in the world of web applications.

    why do you open and close the php tags all the time ? why not just have them at the begging and the end of the document ? would that not be a lot easier ?

    you use the php tags very heavily.

    regards christen

    • Jitu

      @Christen Thanks for the great tip. I would keep this in mind when developing. I have been doing this from last 2 years so it will be tough to get rid of it, but I will try my best!

      Once again thanks for the tip!

  29. Anthony

    Jitu, you’re amazing. I anxiously checked back to see if you were able to offer more assistance and I’m pleased to say things are working as intended. Thank you again!

    • Jitu

      @Anthony Glad that your problem is solved! Do let me know just in case you get into any other problem with the code!

  30. Anthony

    Jitu,
    Thanks for responding! I wasn’t sure if you were referring to fbconnect.php as I do not have a fbaccess.php, but I was not able to successfully complete the task using fbconnect.php.

    • Jitu

      @Anthony oh sorry for the wrong filename. The file is indeed fbconnect.php I have tried it at my side and it works perfectly. I would repeat the changes that i did to make it function
      1. Create a column named ‘imageurl’ after the ‘bio’ column, before the last column
      2. In fbconnect.php file add the following two lines
      $imgurl = “https://graph.facebook.com/$user_profile[id]/picture?type=large”;
      $imgurli = GetSQLValueString($imgurl, “text”);
      3. Replace the following line
      $iquery = sprintf(“INSERT INTO newmember values(”,%s,%s,%s,%s,’yes’)”,$name,$email,$gender,$bio);
      by
      $iquery = sprintf(“INSERT INTO newmember values(”,%s,%s,%s,%s,%s,’yes’)”,$name,$email,$gender,$bio,$imgurli);

      You could then display the image with the tag. That should be it! Try this and if you still getting any error do let me know

  31. Anthony

    This is great and I have added it to my web site. I would like to customize it further by storing the users profile picture (either object or url string) in the database. Can you tell me what modifications I’d have to make in order to achieve this? Thanks in advance for all consideration!

    • Jitu

      @Anthony This is pretty easy actually. Facebook stores all the images of users profile in a specific link. Storing the link of the image in your database should be good for you. First create a column in your member table. Then, in fbaccess.php page create a new variable as below
      $imgurl = “https://graph.facebook.com/$user_profile[id]/picture?type=large”
      Now insert this variable into the database as you are inserting other data! I hope this helps you!

  32. Maria

    Thank you for this tutorial!

    • Jitu

      @Maria Glad you liked it!

  33. Patriquer

    Hello really nice tutorial thanks you !!
    One question : why i always have to accept permission when i’m login in ? normaly you answer one time and after when you login they dont ask again…
    Tha,k you

    • Jitu

      @Patriquer That should not be happening. Maybe there might be some saved settings in your facebook account so that you are getting asked again and again!

  34. Recco

    @ jitu i found this around the web: http://xenforo.com/community/threads/php-5-4-bug-fatal-error-class-not-found.35278/ in this thread they say its a bug because of php version 5.4 (facebook uses 5.3 they say) my xampp runs with php 5.4 so this might be the reason of why the error message comes around but i still dont know how to fix it because i think its not a good idea to use a xampp version with php 5.3

  35. Recco

    @ jitu yes i stopped and startet after the change

  36. Recco

    @jitu i made the change and uncomment the line extension=php_curl.dll but still the same error message if i try to test my page. any other ideas how i could fix the problem?

    • Jitu

      @Recco I have tested this on Wamp Server. I will have to test this thing out on XAMPP to get the better idea of the error you are getting. I would be able to do that in a day or two and would get back to you!

    • Jitu

      @Recco Did you Stop and then start the Apache service of the XAMPP after uncommenting the line extension=php_curl.dll? Without doing that the changes would not appear!

  37. Recco

    Hello at first thanks for the tutorial!
    i have downloaded the tutorial files and made the changes in the download package. i have placed the downloaded files in “G:\xampp\htdocs\facebook-connect-tutorial\” but if i try to test the page by typing “localhost/facebook-connect-tutorial/index.php” in my browser (Firefox) it always says: “Fatal error: Class ‘Facebook’ not found in G:\xampp\htdocs\facebook-connect-tutorial\fbconnect.php on line 15”.
    i think it got something to do with the Facebook PHP SDK but don’t know how to fix this problem.
    i thought the needed source files of the Facebook PHP SDK come with the downloadable version of the tutorial and are placed in “G:\xampp\htdocs\facebook-connect-tutorial\src\” (base_facebook.php, facebook.php and fb_ca_chain_bundle.crt) so is there anything else that might be responsible for the error message? and what shall i do to fix it and get it working?

    • Jitu

      @Recco I think the problem might be that the cURL extension may not be enabled in your XAMPP. In XAMPP installation directory, open %XAMPP_HOME%/php/php.ini file. Uncomment the following line: extension=php_curl.dll This might do the trick for you. Let me know whether this worked for you or not!

  38. Rituraj

    hey yaar nice tutorial..
    I wanted to know that whether i can test this on a free hosted webste
    becoz it redirects back to the same url while testing in localhost(WAMP server) and no information is updated… And if i taking a free domain facebook shows site is not authentic…
    please help me

    • Jitu

      @Rituraj You can easily test this on any kind of website. You have to make specific changes to your facebook apps. If you are testing on localhost or on any website you need to make two changes, first change the siteurl variable in the fbaccess.php page and second go to https://developers.facebook.com/apps and changes the website URl to your site url. This is very important. If you are testing the Facebook connect on a website and the URL in the Facebook Apps page is that of the localhost then you will be redirected to your Localhost page. Make the proper changes and then let me know if this works for you or not!

Leave a Reply