Facebook Connect Tutorial



This tutorial will guide you to the process of integration of your web community with Facebook. This means that when a visitor comes to your site it can log in with normal credenditals if it has, but if it has not it can click on the “facebook connect” button and try to log in with its facebook account, automatically.

This is a good thing because, of course, your community is not so big and famous that every visitor wants to register and become a user to leave just a comment, but probably your visitors already have a Facebook account. So why loose their comments?
More: you can use facebook connected users to post automatically on users’s facebook walls, that is to say, you can increase your traffic.

The target is to add facebook connect functionality with small changes to your code, we also want to make very small changes to your database and to your normal login process.

1. Create an application on Facebook
2. Copy on your site the xd_receiver.htm file
3. Download the PHP apis for facebook and copy them to your site
4. Modify your users’ table
5. Create a PHP page for log in with facebook connect
6. Link the fbclogin.php file to your login
7. Further implementations in the next posts/pages of this blog

So let’s start:

STEP 1. Create an application on Facebook

This means that you have to be registered and logged-in on Facebook, than you have to go to the developer page on facebook and click on the “set up new application” button.
In the set up page you have different fields to enter, but only these ones are needed to make a facebook-connect application for our purpose:
a. “name of the application” and your developer contact in the Main Panel;
b. “Connect url” in the Facebook Connect Panel, you should enter the root of your community site, for the example: http://www.your-site-url.com
c. you can customize log (not necessary)

Save the changes.
This will create a couple of keys that you will use inside your PHP login page: API Key and secret. Copy them or leave this window open to copy them later.

STEP 2. Copy on your site the xd_receiver.htm file

This file is also called “cross domain communication channel” and it’s a static file which include some javascript from facebook servers. The job of this file is set up cookie of Facebook on your domain. It’s necessary because cookies are linked to the domain of the site that write them, so Facebook cannot add cookies on your site without this. And cookies are necessary because the PHP script that will do the work will read cookies setted up by this file. Your site will call facebook, facebook will ask for password if the user isn’t yet logged in, and facebook will call xd receiver to set up cookies on your domain. Finally PHP script will read the cookie that say “logged on facebook ok!”.

Here is the xd receiver file: (you can find it here)

Cross-Domain Receiver Page

<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?2"></script>

STEP 3. Download the PHP apis for facebook and copy them to your site You can download the PHP API here on Github server. You can find the previous link in the get started page of Facebook developers page. STEP 4. Modify your users’ table This is important: we want to let connect the guys of facebook, but we also want to make new users, so we create new users on our community for every new guy coming from facebook. We suppose that you already have a users’ table on your db:

TABLE users (something like this):

username	VARCHAR
password	VARCHAR
email		VARCHAR
status		ENUM ('active','pending','deactivated')
activationdate	DATETIME

If you have the primary key on the email field, than you will have to remove it and use an autoincrement key because you will not receive the email from facebook, the users coming from facebook do not have the email field filled at the beginning. So they are “different”. Add those fields to your users table:

fb_userid	VARCHAR
fl_facebook	ENUM ('new','normal','registered') DEFAULT = 'registered'

the fb_userid will store the facebook user id. the fl_facebook is a flag and the values can be: registered = is the default value that identify your users normally registered on your db new = for new users just created normal = for users that have been transformed into normal users (this could happen later, when you will ask the email to those users to make some action that only registered users can make on your site… for example buy a thing, subscribe to a newsletter, create a new item…), when they become ‘normal’ they are no longer ‘different’. STEP 5.create a PHP page for log in with facebook connectHere it is the code of the facebook login file (fbclogin.php), put it on your web site root (below some note) and read it because it’s full of comments:

<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>


if($fb_user) {
 // if we already have a user ID cookie than we link
 // in the database this user with his facebook account
 // using the fb_userid field.
 // this code assumes that when a user login in your
 // community you set up a value in a cookie called "myid".
 // this cookie is the one that you use when you want
 // to remember the user:
 if ($_COOKIE["myid"]) {
 //$rs = mysql_query( "select * from users where id <>'".$_COOKIE["myid"]."' and fb_userid='".$fb_user."'" );
 //$r = mysql_fetch_array($rs);
 mysql_query("update users set fb_userid='{$fb_user}' where id='".$_COOKIE["myid"]."'");
 // with the user id from facebook retrived with the API,
 // search for a user already registered with this process:
 $rs = mysql_query( "select * from users where fb_userid='$fb_user'" );
 if (mysql_num_rows($rs)) $u = mysql_fetch_array($rs); else $u="";
 if (is_array($u)) {
 // this is a user connected with facebook
 // and already existing on your community.
 // So, log in automatically with user and password of
 // your community. These lens print a form and submit it
 // to your real login page:
 // (change the address in the action to match your normal login page)
 $out.="log in...";
<form id="loginform" action="\&quot;http://www.your-site-url.com/login.php\&quot;" method="post">";
 $out.="<input type="hidden" name="user" value="\&quot;&quot;.$u['username'].&quot;\&quot;/" />";
 $out.="<input type="hidden" name="pass" value="\&quot;&quot;.$u['password'].&quot;\&quot;/" />";
$out.="<script type="\&quot;text/javascript\&quot;">// <![CDATA[
// ]]></script>";

 } else {
 // this is a user logged in on facebook
 // but it doesn't exists on your community,
 // it's new!
 // So let's create automatically the user and log in!
 $out = '';
 // get some user details from facebook api
 $user_details = $fb->api_client->users_getInfo($fb_user, array('last_name','first_name'));
 // write out some message to welcome the new user:
 $out.= $user_details[0]['first_name']." ".$user_details[0]['last_name'].", welcome on your-site-url.com
 $out.= "creating your account on your-site-url.com... wait...";
 $tempuser = preg_replace("/[^a-z0-9]/i","",strtolower( $user_details[0]['first_name'].$user_details[0]['last_name'] ));
 $found = false;
 while (!$found) {
 // search for a valid username
 // not already used in your community
 // this username is created with first name and last name
 // from facebook and with a counter:
 $user = $tempuser.($i==0?"":$i);
 $rs = mysql_query("select count(*) from users where username='$user'");
 $c = mysql_fetch_row($rs);
 if ( $c[0] >0 ) $i++; else $found = true;
 // generate random password for new user:
 $pass = "fb".rand(1000,2000);
 // empty email:
 $email = "";
 //create the user on your table
 $sql = "INSERT INTO users (" .
 "username, password, name, surname, email, status, activationdate, fb_userid, fl_facebook".
 ") VALUES ('{$user}','{$pass}','".addslashes($user_details[0]['first_name'])."',".
 // new user created, log him in:
 $out.="log in...";
<form id="loginform" action="\&quot;http://www.your-site-url.com/login.php\&quot;" method="post">";
 $out.="<input type="hidden" name="user" value="\&quot;&quot;.$user.&quot;\&quot;/" />";
 $out.="<input type="hidden" name="pass" value="\&quot;&quot;.$pass.&quot;\&quot;/" />";
$out.="<script type="\&quot;text/javascript\&quot;">// <![CDATA[
// ]]></script>";
} else {
 // the user probably isn't logged in on facebook, put out
 // the facebook button and clicking on it it will open a pop uo
 // that requires the login on facebook to proceed.
 // the "onlogin" command refresh the page.
 $out = '
 Click to log on your-site-url.com with your facebook account.

<!--?=$out? -->
<script type="text/javascript">// <![CDATA[
  FB.init("<?=FB_API_KEY?>", "/xd_receiver.htm");
// ]]></script>

This PHP file includes in the header some tag for facebook (the namespace declaration in the html tag), so it can handle FBML code (the facebook specific tags for html facebook elements).
Than it includes a javascript file from facebook which is called at the end with FB.init javascript call.

STEP 6. Link the fbclogin.php file to your login

Near your login fields, add a link to the fbclogin.php file so users will notice suddenly that you give a facebook connect functionality.

STEP 7. further implementations in the next posts

a. copy the avatar from facebook to your server: it’s easy: note, this is not approved by Facebook policies!
b. handle redirect to the correct page: if you have the login in every page you can modify this code to let the user go back to the correct page after the login process.
c. handle duplicated accounts: sometimes a user that connect with facebook already has an account on your site, so you will have two users for the same person on your db. That could be a problem, we will explain why and how to solve the problem.
d. handle registration completed: registration is completed when a user give you every data you consider mandatory, such as the email. This script already handles the flag fl_facebook, but in a further post we will explain how to modify your scripts to handle this part of the process.
e. use facebook connect functions to post to users wall on facebook: this will increase traffic to your site.

Comments on “Facebook Connect Tutorial”

104 thoughts

  1. Thanks, ha! Where’s the subscribe button? :)

  2. Casie Duckworth ha detto:

    Generally I do not post on blogs, but I would like to say that this article really forced me to do so! Thanks, really nice blog.

  3. Sumon ha detto:

    Hi Guys, Thats a nice post

  4. Warren ha detto:

    Hi. Please can you help me out. I am getting this error: Parse error: syntax error, unexpected T_INC in /home/gtownco/public_html/fbclogin.php on line 85
    Thank you.

  5. admin ha detto:

    yes. It’s missing a $. Change i++ with $i++.
    there is also another errror in this line, I miss an “else”. Change the line this way:

    if ( $c[0] >0 ) $i++; else $found = true;

    I’ve fixed it in the post.

  6. Till ha detto:

    Hi, can you please give an example for the settings-and-functions.php?

    It would be great because I am new to PHP and do not know the syntax yet.

    Thanking you in anticipation.

  7. admin ha detto:

    It’s just a file with at least those lines:

    DEFINE("FB_API_KEY" , "value from facebook application setting");
    DEFINE("FB_SECRET" , "value from facebook application setting");
    function ConnectDB() {
    if (mysql_connect( "domain", "user", "pwd" ) && mysql_select_db( "yourdb" )) return 1;	else return 0;

    you’re really a beginner! :-)

  8. Till ha detto:

    Thanks! You are right, I’ve just written my first line of PHP code. :-D

  9. Facebook Apps ha detto:

    Really great post and tutorial to integrate your web app with Facebook using Facebook Connect.
    Keep it up.

  10. friskon ha detto:

    C’è una versione del tutorial in italiano ?
    Ho seri problemi con l inglese, anche se lo traduco con google translate non capisco lo stesso.

  11. Arda Kilicdagi ha detto:

    Hey mate, thanks for this great tutorial. I’ve integrated your tutorial to PHP-Fusion


    Thanks again,
    Arda Kilicdagi aka Soulsmasher

  12. Webbando ha detto:

    Thanks a lot for your tutorial!

    I have a problem: when i go to fbclogin.php I have the followings error:

    Fatal error: Call to undefined function connectdb() in /home/namesite/public_html/forum/fbclogin.php on line 16

    In line 16 there is “if(!ConnectDB()) die;”, what means it?

    Thanks a lot for your support

  13. Arda Kilicdagi ha detto:

    @webbando – you need to create your own mysql connection script or altwer that line with your connection parameter

  14. Webbando ha detto:

    @Arda – I don’t undestand which is settings-and-functions.php file also…

  15. admin ha detto:

    Settings and functions is a file that you have to write by yourself, this file should include at least the connectDB function to connect to your database and everything you need to work with your db.

  16. Imran S ha detto:

    Great post! Any more info on..

    “c. handle duplicated accounts: sometimes a user that connect with facebook already has an account on your site, so you will have two users for the same person on your db. That could be a problem, we will explain why and how to solve the problem.”

  17. Waseem ha detto:

    hi , Thanks for the great tutorial
    but how about the log out ?

  18. Lucifix ha detto:

    Is there something wrong with Facebook server but this link is dead:

  19. DiegoT ha detto:

    Hello! About these two lines:

    You can download the PHP API here on Facebook servers.
    You can find the previous link in the get started page of Facebook developers page.

    The first line is a dead link. The second one takes me to a page but I don’t understand what I am supposed to download. Could you please maybe update the link? Thank you very much

  20. Mariano ha detto:

    Facebook moved the source api to GitHub. The new url to download the php api is this one: http://github.com/facebook/php-sdk/blob/master/src/facebook.php.
    Here are some example codes: http://github.com/facebook/php-sdk/, but this post if by far superior. Great work.

  21. fulgorek ha detto:

    works perfectly just have some issues with cookies.

  22. fulgorek ha detto:

    wow, just works for first user, second time don’t insert on database, any idea how to fix it?

  23. Gwen ha detto:

    Can you provide some help with disconnecting from Facebook? It seems no matter what example I try from searching Google, nothing logs out of Facebook. I am looking for something to put in my logout.php page and redirect it to login.php. FB.Connect.logoutAndRedirect doesn’t seem to do ANYTHING.


  24. Gwen ha detto:

    Nevermind, I found something that works perfectly:

    window.onload = function(){
    // we are logged out of facebook, erase my app’s cookie
    var name = “name_of_my_session_cookie”;
    document.cookie = name +’=;expires=Thu, 01-Jan-1970 00:00:01 GMT’;
    //refresh the main page
    var url = window.parent.location.href;
    // append a timestamp to make sure the url seems different to the browser
    url = (url+(url.indexOf(‘?’) > -1 ? ‘&’ : ‘?’)+(new Date()).getTime());
    window.parent.location.href = url;
    Found at http://forum.developers.facebook.com/viewtopic.php?pid=119774#p119774


  25. lenna ha detto:

    im missing the point at line 34 of the main script

    i assume this line connect my facebook user to my currenty logged user

    that way… the query returns 0 lines, maybe you should check with an = for the cookie-user_id pair and with for the fb_userid

  26. lenna ha detto:

    just another thing
    the env var for cookies is $_COOKIE not $_COOKIES ;)

  27. admin ha detto:

    yeah! True! I’ve fixed it. Thank you. :-)

  28. admin ha detto:

    You’re right! Sorry for that error. You can remove line 34 and 35 (I’ve commented) because they are part of a solution for the problem described in STEP 7, part C. I’ve not yet posted it.

  29. admin ha detto:

    MMmm since with this tutorial I bring the users to create a new account on my site… I don’t matter if they are still logged in into facebook. Or not?

  30. admin ha detto:

    Probably because I wrote $_COOKIES instead of $_COOKIE?

  31. marco ha detto:

    ciao, ho un sito ma non riesco ad integrare perfettamente facebook connect, perché non so o bravissimo!!!

    qualcuno può darmi una mano!??!?

    sapete come poter far accedere al sito anche con un account google??


  32. Jose ha detto:

    Como hago para solucionar el paso 7 C), para no tener usuarios duplicados en mi base de datos. Muchas gracias.

  33. vicky ha detto:

    getting this error
    Fatal error: Call to undefined method Facebook::get_loggedin_user() in C:\xampp\htdocs\testing\facebookconnect\fb_connect\connect\fbclogin.php on line 21

  34. vicky ha detto:

    $_COOKIE[“myid”] is not getting any value so the users table is not updating on localhost

  35. Giulio Pons ha detto:

    Vicky you have to implement by yourself that part, this code is not “ready to use”, but you have to customize it on your needs. That id stored in the cookie is the id of your user when it normally log in (you should have a mechanism that handle logged in user id).

  36. Alex ha detto:

    Had the same problem myself. Found a quick fix for it.

    Change line 21 from:




    That should fix the error.

  37. Alex ha detto:

    Quick question for you Giullo…..

    I’m trying to request extended permissions from Facebook, but no matter where I put the perms=”email,user_birthday,etc…” line, it won’t take it. I put a “req_perms” argument in the seemingly designated place (as noted by a comment in the code) in facebook.php and it still won’t take. I just get the same old “**** is requesting to do the following: access my basic information” when I click the connect button displayed on fbclogin.php.

    Any ideas?


  38. Marlyn ha detto:

    I am gettin this error!!

    Fatal error: Cannot redeclare class FacebookApiException in D:\wamp\www\books\connect\facebook.php on line 70

    Pls help me :(

  39. Marlyn ha detto:

    Fatal error: Call to undefined method Facebook::get_loggedin_user() in D:\wamp\www\books\connect\fbclogin.php on line 21

    PLS HELP ME :(

  40. Giulio Pons ha detto:

    Read the comments: facebook has modified its class, so there is a different method!

  41. Marlyn ha detto:

    I am a total beginner on this..

  42. Giulio Pons ha detto:

    Marlyn, read comment number 48 from Alex. :-)

  43. Jaime ha detto:

    when I click on the button “Connect” window opens and then closes, why?

  44. Steven ha detto:

    I cannot get this to work for the life of me. I have a very simple members table in my mysql database.. its getting very frustrating.. can anyone help me with this simple task? please email admin@scautonow.com

  45. Justen Doherty ha detto:

    Hi All, after wrestling with this awful code for more than an hour i found this code on github: http://github.com/facebook/php-sdk/

    there’s a download button on the page if you are unfamiliar with git and i was up and running in a matter of minutes

  46. Glenn ha detto:

    Step 1 is outdated or something
    you say: “Connect url” in the Facebook Connect Panel

    But nowhere on the application creation do either of these things exist?!

    So i cannot go past the first few lines of your wonderful tutorial

    Have facebook changed?

  47. Giulio Pons ha detto:

    Probably yes, it’s changed.

  48. Jim Bower ha detto:

    Just some friendly advice,

    I just spent over 2 hours trying to get this working without any luck,
    You might wanna write something like “THIS DOES NOT WORK ANYMORE, FACEBOOK HAS CHANGED” at the top of the page. Or update the content so it will work.


  49. Red social ha detto:

    Claro que si funciona, yo lo hice para conectarse con mi red social directamente desde tu perfil de facebook, si quieren vean y se convencerán: http://directorio.a60.us/jcow/ dice conectar básico y con facebook, así que amigo de verdad te agradezco por tan valioso aporte que me sacó de apuros. Los que no saben inglés sugiero que utilicen el navegador de google chrome que viene integrado con un traductor automático

  50. bright led ha detto:

    Great article and right to the point. I am not sure if this is actually the best place to ask but do you folks have any thoughts on where to hire some professional writers? Thank you :)
    led flashlight

  51. Online Fashion ha detto:

    Yes Facebook has changed,

    (Sorry for Caps)

  52. Giulio Pons ha detto:

    It still works for me, but probably it doesn’t works with
    new facebook applications. If you have an old Facebook connect
    application it works, if you’ve registered an application recently
    I think it will not work.

  53. Abdul ha detto:

    how can I connect to authenticate to count user for my facebook community group

  54. Stevie Renfroe ha detto:

    Ingles not me firsd langage but much likey yor blog. Pleze to continyu fine posting and I like try copy,ok?

  55. debajani ha detto:

    Hi All

    I have just created an app on facebook and want to try exactly the same thing as mentioned in the tutorial , but i read the comments and see that this is quite old and might not work for recently creates apps.

    can someone please give any pointer to some other tutorial or guide for facebook connect to work in website?

    PLS HELP !!!


  56. Belak ha detto:

    I can see you’re an expert at your field! I am launching a website soon, and your data will likely be really useful for me.. Thanks for all your assist and wishing you all of the success.

  57. fifa 11 ha detto:

    What would all of us do without the amazing concepts you talk about on this website? Who has the fortitude to deal with vital topics just for common subscribers like me? My spouse and i and my buddies are very blessed to have your web blog among the types we often visit. Hopefully you know how a great deal we value your effort! Best wishes through us all.

  58. 2ne1 ha detto:

    A lot of thanks for your own efforts on this blog. Kate takes pleasure in managing research and it is easy to see why. We hear all of the lively way you create simple tricks through your web blog and as well strongly encourage response from other ones about this topic while our favorite child is undoubtedly discovering a lot. Enjoy the rest of the year. You’re the one conducting a terrific job.

  59. Torrent Marketing ha detto:

    This design is spectacular! You obviously know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  60. 關鍵字行銷 ha detto:

    Hey there dude, I am seeking help on the ideas about website design. Your site is quite well on this issue. Would you mind writing more about how you make this? Thanks.

  61. www.esa-egypt.com/diving-forum/member.php?u=456289 ha detto:

    Excellent post. I was checking constantly this blog and I am impressed! Extremely helpful info particularly the last part :) I care for such info much. I was looking for this particular info for a very long time. Thank you and best of luck.

  62. pyjama ha detto:

    What? Hello. Awesome Job once again. I like coming to your site because the writers usually provide well written articles. Supreme blog post…I plan to add this blog to my faves. I am planning to subscribe to the websites feed as well. Recently purchased a brand new cellphone ! Any one own new iphone4?? It is so nice…..

  63. Faceboo ha detto:

    Congratulations, your blog has all the credentials to be one of the best on the web.

  64. News ha detto:

    I similar to your blog, and also including the article, and thank you for provide me much information

  65. I do believe many people would certainly concur with you

  66. gary ha detto:

    amigo donde esta el archivo settings-and-functions.php

  67. alain ha detto:

    its possible to integrate the login button in my site http://www.occasioneonline.com ?

  68. MdAmor ha detto:

    Can you update this for the new fb:registration button?

  69. Giulio Pons ha detto:

    I’m sorry, but I can’t update any post for some months. Sorry.

  70. Giulio Pons ha detto:

    I think you have to read the facebook documentation, since this page became old and it seems it doesn’t work anymore.

  71. Giulio Pons ha detto:

    it’s a your page with basic settings and functions…

  72. Earlean Laforge ha detto:

    keep them comming

  73. LysLin ha detto:

    Aw, this was a really nice post. In thought I would like to put in writing like this moreover – taking time and precise effort to make an excellent article… however what can I say… I procrastinate alot and not at all appear to get something done.

  74. You should take part in a contest for top-of-the-line blogs on the web. I’ll advocate this site!

  75. Towanda Anzualda ha detto:

    Wow you hit it on the dot we shall submit to Plurk in addition to Squidoo well done انواع محركات الطائرات | هندسة نت was wonderful

  76. Leena Lievsay ha detto:

    Hey there guys, newbie here. I’ve lurked about here for just a little although and thought I’d take part in! Looks like you’ve got quite a very good spot here

  77. Chris ha detto:

    Use $fb->getUser() instead of $fb->get_loggedin_user(); in line 21. This helps.

  78. Nayan ha detto:

    i cannot find settings-and-functions.php
    it gives me errors

    Warning: include(settings-and-functions.php) [function.include]: failed to open stream: No such file or directory in C:\AppServ\www\phase2.3\fbclogin.php on line 10

    Warning: include() [function.include]: Failed opening ‘settings-and-functions.php’ for inclusion (include_path=’.;C:\php6\pear’) in C:\AppServ\www\phase2.3\fbclogin.php on line 10

    Fatal error: Call to undefined function ConnectDB() in C:\AppServ\www\phase2.3\fbclogin.php on line 16

  79. Omnia Software ha detto:

    Con il nuovo SDK abbiamo problemi mentre con la versione precedente funziona perfettamente

  80. Optiker Stockholm ha detto:

    F*ckin? awesome things here. I?m very happy to look your article. Thanks a lot and i’m having a look ahead to touch you. Will you kindly drop me a e-mail?

  81. เย็ด ha detto:

    Warning: include(settings-and-functions.php) [function.include]: failed to open stream: No such file or directory in C:\AppServ\www\phase2.3\fbclogin.php on line 10

  82. serambi indonesia ha detto:

    It seem difficult for me

  83. aste gratis ha detto:

    Vorrei inserire il login button sul mio sito di aste, ma non riesco.

  84. Chris ha detto:

    Awesome tutorial! I was able to implement it successfully on one of my new sites.

  85. Picasso ha detto:

    Thank’s !! :D

  86. Janet ha detto:

    Question: so, if I access someone’s FB site this way (php), they essentially can monitor who is viewing their site in this manner? In other words, they can see how many times I or someone else accesses their site?

  87. Ashok ha detto:

    This is very good topic.
    this is important for me and programming blog

  88. iie ha detto:

    hey guys check this out
    its very easy to integrate

Comments are closed