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. harpreet

    My website is in word press . i implemented your code in my WordPress template file but it does not save Facebook user into my data base please help me out for it

  2. Abner

    site_name/index.php?code=AQAb3SWOrfDH0_JYbQj1fTfNyF2YM9fW7G1dvEn6KcrmTOfKtJRfKOAYxPFs1AjWHQi8h1qH24kRkn-H06aKFNz9AIsbv_YrrDaFLg6YSgTzlt4YKhFqVZRI9soBX-7c_CL4SFq7084ZZ7gT2SbSxRGpbuHVY0x2i3tQeAAu-Ni61cnJoiNxa84kDHK6ZP2_T-HfUNxHWUyf_Fzd6STfQEXA&state=f52ad314c632b361d8065edab6c48f2f#_=_

    i get this code, cannot redirect to index.php..please help and nothing stored in db

  3. pierre

    Don’t work for me.

  4. David

    Hi..great tutorial !! I am working on an app and am using a similar mechanism, although using the Javascript SDK.

    My question is regarding step # 9 and is more theoretical: It says” 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…”

    Why are you checking if their ‘email ‘ exists in your DB?…Wouldn’t it be better to check whether or not the user’s Facebook ID exists in your DB (given of course you stored it the first time around the user authenticated your app?) – …i mean..what would happen if the user changes their email they have stored in fb??….you would query your db with the ‘new’ email address which is passed from FB….this would result in an empty recordset, even though the user does exist!…

    I was planning on doing basically the same thing but using the user’s FB id, which is unique and never changes…

    Please let me know what you think!?!?….

    David

  5. Ruturaj

    i had just change the site url to solve this kind of erro we have to provide same url in fbconnect file as we had given during app creation….
    and one more the coloumn name should b same as in db and in fbconnect file…

  6. Ruturaj

    Hey @jitu problem solved it’s working properly thanx dude !!!!!!!!!

    • Jitu

      @Ruturaj How did it get solved? If you could specify the steps, everyone could know what to do on getting the same type of error!

  7. Eashwar

    An error occurred. Please try again later.

    pls help me to solve this error…

  8. Ruturaj

    Hey thanx @jitu it’s working but it’s not storing any data in my database table and it’s directly ridercting to site url.. pls help me it’s very imp 4 me….

  9. Rutruaj

    Hey @jitu thnaks it’s working but session is not starting means it’s directly redirecting to site url and it’s not storing any data in d/b table pls one more time help me nd thanks in advance…

  10. sandeep

    I can successfully login using the above code, but nothing is getting stored in the database..I ‘m sure ive replaced everything (appid, apps secret, hostname, db name, pass etc)correctly

  11. sujan

    ( ! ) Notice: Undefined index: email in E:\wamp\www\ffeed\index.php on line 47

    I get null email while inserting the email in my database but all other are inserted in the database what is the problem….This problem occured while accessing the apps with otheres mail or account…ie. after inviting other …

  12. Ruturaj

    hi thanks for tutorial..
    i have implimented the given code but i m getting the follpwing error…pls help me to solve this errorr..

    “The parameter app_id is required”

    • Jitu

      @Ruturaj You need to put in your App ID and App Secret at the start of the fbconnect.php file to make this work!

  13. Ruturaj

    Fatal error: Class ‘Facebook’ not found in C:\xampp\htdocs\fbconnet\fbconnect.php on line 15
    i am getting this error ols giv me solution…

  14. ICE

    Thanks for the tutorial!!!!
    i have downloaded the tutorial files and made the changes in the download package. But I got this erro : Fatal error: Class ‘Facebook’ not found in E:wampwwwfacebook-connectfbconnect.php on line 15 .
    Could you help ?Thanks again !

  15. nicola adamo

    @Leo and @Fabien, i had your same issue and solved calling session_start() before any of the calls to the Facebook object

  16. indonesia air travel

    My programmer is trying to persuade me to move to .
    net from PHP. I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using WordPress on a number of websites for about a year and am concerned about switching to another platform.
    I have heard excellent things about blogengine.net.

    Is there a way I can import all my wordpress posts into it?
    Any help would be really appreciated!

  17. Rafa

    Hello, it seems that facebook connect its working only with my account. Have you seen this before? its on http://www.agenciadobarulho.com.br/connect

    Thank you

  18. paddy

    hi i already have a website with a lot of members and also have a sign in database how can i connect it to that one any help thanks pal

  19. Fabien

    Dear

    I have the same problem, i accept apps => no problem

    I am redirect to my fb connect (site.com/fb) but i am nos loggin …. et in have no data in SQL

    Please can you help us ?

  20. Leo

    Here is a link to the app on my server, test it and see if it works for you or anyone else who wants to try: http://www.pulsarmedia.ca/fbconnect

    thanks.

  21. Leo

    Hi,

    I downloaded your source files and i am testing your application on my server but it doesn’t seem to fully work.

    After i press the CONNECT button i get redirected to facebook, i log into my account, then i get prompted for permissions and then i get redirected back to my domain (the one i specified in my facebook app settings) and it doesn’t show me as logged in…i just continue to see the large CONNECT button and the smaller Login button in the upper right corner.

    Any ideas why it might not be working?

    Thanks.

  22. ZeGuigui

    Thanks, it helped a lot understanding how to put everything together. I managed to integrate most of this into the next version of my website and my existing framework.

  23. Godot

    Same issue here as David.

  24. David

    I am getting nothing in return after accepting permissions. It just goes back to the same page with the login button (which it says login as well in the upper right-hand corner) so it doesn’t seem to be logging me in? “getUser()” seems to be “0″. Does the app itself need to have the permissions set on it with the permissions the code states (read_stream, publish_stream, email, user_about_me) because in your tutorial, you never state to add those to the app itself on FB?

    And as for adding the “session_start();” to the fbconnect.php page.. it makes the page not work.

    Thanks for your time!

  25. John

    As with others above, I am also not able to display or store data. I was able to log in once and give permission to my webapp to access my facebook data, but nothing is showing up on the page other than the original facebook login button.

    Any ideas? Thanks!

    • Jitu

      @John The problem seems to be the session ID’s. I think the session is not getting created properly. Make sure that you have session_start(); at the start of the two files fbconnect.php and index.php That might solve your problem!

  26. diego caballero

    Wow, great tutorial this is exactly what i needed. The only thing I cant get to work is publishing on the users stream or wall.. Right now, i´ve got a user connecting to my site and authenticating, then a poll shows up and the user can vote, when the user votes i want to post it in his/her wall.. And right now thats where im stuck, I would be very greatful if you could you give me an insight! Thanks a lot!

  27. Nina

    Love the script and I have found a way to get the facebook login to work, however it is not storing the data into the database. I ‘ve also used the latest updated src files from Github. I am not returning any connection errors. When I search the database after I log in, here are the results:

    MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0003 sec )

    Am I missing something?

  28. arush

    Hey Jitu i get an error “An error occurred. Please try again later.” Please help me

    • Jitu

      @Arush At what stage are you getting this error. Could you please specify the steps that you have completed?

  29. Bhupendra

    Hi

    I have used your code and uploaded to my website, but the record are not being inserted into database

    the website where i am using your code charkhaa dot com/fb

    please do needfull

    thanks
    Bhupendra

    • Jitu

      @Bhupendra FB is accepting the requests perfectly. Maybe there is something wrong at your DB side. Check if all the fields are proper and in the same order and also check if the code is creating sessions properly!

  30. julien

    you are definitly a genius, thank you so much for your help, your tuto is just awsome!!!

  31. Ajoshi31

    Bingo..

    its working smooth and coool

    Thanks Jitu
    @ashvin check if you have unchecked the sandbox checkbox it is for admin access only

    hope it will work…

  32. Ajoshi31

    @ashwin its not taking for the one who did not make the app.. just for the id made for the app

  33. Ajoshi31

    Hey Thanks..
    I did that yesterday..
    changed the ini file config also and all went fine..

    but still having a bit diff problem..like first time it worked all fine for me..
    checked the id in database and then went to INSERT it into dbbut next when I tried with another id I am having the same problem as @ashwin..

    http://www.ashwinisingh.in/fb_connect/

  34. manos

    Dear Jitu,
    thank you very much for the very helpful tutorial !!!
    Works just fine :D

    • Jitu

      @Manos Glad to be of help!

  35. Ajoshi31

    Hi I just tried but dont know it is not tacking the Facebook class and throwing up the error class not found in fbconnect.php page ..

    try{
    include_once “src/facebook.php”;
    }catch(Exception $e){
    error_log($e);
    }
    // Create our application instance
    $facebook = new Facebook(array(

    • Jitu

      @Ajoshi31 you need to download the PHP SDK from the github page and then include the “base_facebook.php” and “facebook.php” files in the “src” folder. Then the code would work perfectly

  36. Shiv Singh

    If you are want to use it on localhost than first update your file after downloading new PHP SDK from https://nodeload.github.com/facebook/facebook-php-sdk/zip/master and Past new files from src than its working.

  37. topherstiles

    Will the users info be stored on my database that I can later export as a .csv?

    Thanks!

  38. nickyb

    Solved it! I had to set a cookie to expire. If anyone is having similar issues this helped a lot:
    http://samoldak.com/fixing-facebooks-php-sdk-logout/

  39. nickyb

    NOTE: I also tried disabling everything on the page except for the relevant FB Connect code and still had no luck getting this thing to connect.

  40. nickyb

    I’m going nuts trying to get this to work on my live server. Everything worked great on my private testing server, but the login is not working on the live server.

    For some reason the login/logout url’s just display the redirect url and simply refreshes the page. Any ideas?

    I noticed a couple other people have mentioned similar issues here.

Leave a Reply