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

    the values are not storing in database…i am using this in wordpress site

  2. bhargav

    i am not able to store the user info into the database, i can login , but after login …no values are there in database….please help me

  3. Simon

    that’s no more good, coz sdk’s deprecated

  4. Rocky

    Plz Help me how to show, facebook Connnent in dialog box ???

  5. shashank

    if you could please resolve dis for me:
    I downloaded your app and did the specifies changes but the values are not fetched from facebook.
    Note that i am running it on localhost.
    is there any issue with extended permission with localhost.
    session is not created so it came back to index page with no info fetched

  6. manas singh

    It good tutorial. I have used this code and it work fine
    Thanks…

  7. Mohamed

    @Rituraj @David be sure of $site_url value ends with ” / ”
    Ex.: $site_url = ‘http://www.domain.com/demo/’;

    It is working for me :)

  8. azhar

    following error occure

    Fatal error: Class ‘Facebook’ not found in C:\wamp\www\facebook-connect-tutorial\fbconnect.php on line 15

    how to debug this?

  9. Felipe

    Hey Awsome post. I was struggling on how to save the credentials when is was logged in. Never thougt about using if(!isset($_SESSION['user'])).

    Thanks again.!

  10. Sebastian

    I have a question, is it possible to log out from Facebook as well?
    So when I revisit my page I can log in with a different Facebook account?
    Now if I want to log in again, it auto logs in, so you can’t log in with a different Facebook account.

    Can you please help, thank you?

Leave a Reply