Create Facebook PopUp Authentication Window using PHP and javascript

facebookSome days ago one of my friends Paul Espino asked me that he is facing a problem of redirection loop.  He followed exactly my article php sdk & graph api based fb connect tutorial but in his server when user logged in via facebook connect by clicking javascript base fbconnect button the login() method of below code called again and again

FB.Event.subscribe('auth.login', function(response) {
    // do something with response
     login();
});
function login(){
    document.location.href = "<?=$config['baseurl']?>";
}

I tested the code in various server but the problem occurs only in his server. Then I think to solve the problem using php-sdk generated login code.

In the official example you’ll see the code

<?php
if ($me) {
     $logoutUrl =   $facebook->getLogoutUrl();
} else {
     $loginUrl   =   $facebook->getLoginUrl();
}
?>
<?php if ($me): ?>
    <a href="<?php echo $logoutUrl; ?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
    </a>
    <?php else: ?>
    <div>
      <a href="<?php echo $loginUrl; ?>">
        <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
      </a>
    </div>
    <?php endif ?>

But there is a problem, that is if you use the technique then when user will click login he will redirect to the $loginUrl generated by facebook i.e his main browser window’s url will change. But I want, this authentication will happen in javascript popup window as like as javascript sdk based authentication by facebook. And at last I solved it by the following way:

Check The Demo First

Logic behind popup authentication using php and javascript:

  1. User first click FBConnect Login Button
  2. I’ll create a javascript popup window and load the login url there
  3. When user successfully authenticate there then facebook will redirect him to the ‘next‘ url passed by me. The redirect will still happen in the popup window.
  4. I’ll also pass a special parameter with ‘next‘ url’s parameter, so when user redirected here I’ll first collect session variable (Facebook sends a session json encoded string) I’ll modify them to a special format and save the value as a cookie.
  5. Then I’ll close the popup window and browser’s main window will reload.

The procedure is same as my previous article just I modified the index.php

Step 1: Generate login/logout url by php

     $config['baseurl']  =   "http://thinkdiff.net/demo/newfbconnect1/fbpopup/index.php";

    // login or logout url will be needed depending on current user state.
    if ($fbme) {
      $logoutUrl = $facebook->getLogoutUrl(
        array(
            'next'      => $config['baseurl'],
        )
      );
    } else {
      $loginUrl = $facebook->getLoginUrl(
        array(
            'display'   => 'popup',
            'next'      => $config['baseurl'] . '?loginsucc=1',
            'cancel_url'=> $config['baseurl'] . '?cancel=1',
            'req_perms' => 'email,user_birthday',
        )
      );
    }

If you look carefully you’ll see I passed the next parameter for both login and logout url.

$config['baseurl'] . '?loginsucc=1'

this is mandatory because we will open the login procedure in javascript popup. So after login successfully in the popup window facebook url will redirect to next url, so when I’ll get loginsucc parameter I’ll close the popup window.

And also look

'cancel_url'=> $config['baseurl'] . '?cancel=1',

If user click cancel then I redirect him to this url. So that I check whether user click cancel or not.

Step 2: Add this code just after step1’s code

//if user click cancel not login, then i just close the popup window
 if (isset($_REQUEST['cancel'])){
        echo "<script>
            window.close();
            </script>";
}

//only if valid session found and loginsucc is set
if ($fbme && isset($_REQUEST['loginsucc'])){
        //after facebook redirects it will send a session parameter as a json value
        //now decode them, make them array and sort based on keys
        $sortArray = get_object_vars(json_decode($_GET['session']));
        ksort($sortArray);

        $strCookie  =   "";
        $flag       =   false;
        foreach($sortArray as $key=>$item){
            if ($flag) $strCookie .= '&';
            $strCookie .= $key . '=' . $item;
            $flag = true;
        }

        //now set the cookie so that next time user don't need to click login again
        // cookie name should be fbs_ + application id
        setCookie('fbs_' . "{$fbconfig['appid']}", $strCookie);

        echo "<script>
            window.close();
            window.opener.location.reload();
            </script>";
    }

This code checks for $fbme and $_REQUEST['loginsucc'] parameter. If it finds ok, then it first collects the value session sent by facebook. It is a json encoded string.  Next

$sortArray = get_object_vars(json_decode($_GET['session']));

json_decode() php function decodes json encoded string and returns a object, then get_object_vars() converts the object to associative array. Then I sort the array based on keys by ksort() php function. Next I make a string $strCookie based on the keys and values of $sortArray and save the $strCookie as cookie.

Then I will close the popup window and reload the main window.

Step 3: Now add this javascript code

<script type="text/javascript">
        <?php if ($loginUrl) { ?>
        var newwindow;
        var intId;
        function login(){
            var  screenX    = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
                 screenY    = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
                 outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth,
                 outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22),
                 width    = 500,
                 height   = 270,
                 left     = parseInt(screenX + ((outerWidth - width) / 2), 10),
                 top      = parseInt(screenY + ((outerHeight - height) / 2.5), 10),
                 features = (
                    'width=' + width +
                    ',height=' + height +
                    ',left=' + left +
                    ',top=' + top
                  );

            newwindow=window.open('<?=$loginUrl?>','Login_by_facebook',features);

        	 if (window.focus) {newwindow.focus()}
        	return false;
        }

        <?php } ?>

Though this is javascript code but it is rendered by php. So I added a php if logic. Please note that in the second parameter there should be no space “Login_by_facebook” not “Login by facebook”, because, if that contains space IE shows javascript error. But other browser will not complain.

newwindow=window.open('<?=$loginUrl?>','Login_by_facebook',features);

This is the code that will open the popup window. features is a string that contains some parameters for the outlook of the popup window.

Step 4: Add this html code of the login/logout buttons

       <?php if ($fbme) { ?>
            <a href="<?=$logoutUrl?>">
              <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif" border="0">
            </a>
        <?php } else{ ?>
            <a href="#" onclick="login();return false;">
              <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif" border="0">
            </a>
        <?php } ?>

That’s it. Check the demo its exactly looking the same as facebook javascript based authentication window.

And this technique also solved my friends problem of redirecting issue.

Download fbmain.php from here and facebook.php from facebook

Full Source Code of index.php

<?php
    include_once "fbmain.php";
    $config['baseurl']  =   "http://thinkdiff.net/demo/newfbconnect1/fbpopup/index.php";

    // login or logout url will be needed depending on current user state.
    if ($fbme) {
      $logoutUrl = $facebook->getLogoutUrl(
        array(
            'next'      => $config['baseurl'],
        )
      );
    } else {
      $loginUrl = $facebook->getLoginUrl(
        array(
            'display'   => 'popup',
            'next'      => $config['baseurl'] . '?loginsucc=1',
            'cancel_url'=> $config['baseurl'] . '?cancel=1',
            'req_perms' => 'email,user_birthday',
        )
      );
    }

    // if user click cancel in the popup window
    if (isset($_REQUEST['cancel'])){
        echo "<script>
            window.close();
            </script>";
    }

    if ($fbme && isset($_REQUEST['loginsucc'])){
        //only if valid session found and loginsucc is set

        //after facebook redirects it will send a session parameter as a json value
        //now decode them, make them array and sort based on keys
        $sortArray = get_object_vars(json_decode($_GET['session']));
        ksort($sortArray);

        $strCookie  =   "";
        $flag       =   false;
        foreach($sortArray as $key=>$item){
            if ($flag) $strCookie .= '&';
            $strCookie .= $key . '=' . $item;
            $flag = true;
        }

        //now set the cookie so that next time user don't need to click login again
        setCookie('fbs_' . "{$fbconfig['appid']}", $strCookie);

        echo "<script>
            window.close();
            window.opener.location.reload();
            </script>";
    }

    //if user is logged in and session is valid.
    if ($fbme){
        //Retriving movies those are user like using graph api
        try{
            $movies = $facebook->api('/me/movies');
        }
        catch(Exception $o){
            d($o);
        }

        //Calling users.getinfo legacy api call example
        try{
            $param  =   array(
                'method'  => 'users.getinfo',
                'uids'    => $fbme['id'],
                'fields'  => 'name,current_location,profile_url',
                'callback'=> ''
            );
            $userInfo   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }

        //update user's status using graph api
        if (isset($_POST['tt'])){
            try {
                $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> $_POST['tt'], 'cb' => ''));
            } catch (FacebookApiException $e) {
                d($e);
            }
        }

        //fql query example using legacy method call and passing parameter
        try{
            //get user id
            $uid    = $facebook->getUser();
            //or you can use $uid = $fbme['id'];

            $fql    =   "select name, hometown_location, sex, pic_square from user where uid=" . $uid;
            $param  =   array(
                'method'    => 'fql.query',
                'query'     => $fql,
                'callback'  => ''
            );
            $fqlResult   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }
    }
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Create your own Facebook PopUp Authentication Window using php and javascript | Thinkdiff.net</title>
    </head>
<body>
<style type="text/css">
    .box{
        margin: 5px;
        border: 1px solid #60729b;
        padding: 5px;
        width: 500px;
        height: 200px;
        overflow:auto;
        background-color: #e6ebf8;
    }
</style>
    <script type="text/javascript">
        <?php if ($loginUrl) { ?>
        var newwindow;
        var intId;
        function login(){
            var  screenX    = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft,
                 screenY    = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop,
                 outerWidth = typeof window.outerWidth != 'undefined' ? window.outerWidth : document.body.clientWidth,
                 outerHeight = typeof window.outerHeight != 'undefined' ? window.outerHeight : (document.body.clientHeight - 22),
                 width    = 500,
                 height   = 270,
                 left     = parseInt(screenX + ((outerWidth - width) / 2), 10),
                 top      = parseInt(screenY + ((outerHeight - height) / 2.5), 10),
                 features = (
                    'width=' + width +
                    ',height=' + height +
                    ',left=' + left +
                    ',top=' + top
                  );

            newwindow=window.open('<?=$loginUrl?>','Login_by_facebook',features);

        	 if (window.focus) {newwindow.focus()}
        	return false;
        }

        <?php } ?>
    </script>

    <h3>Create your own Facebook PopUp Authentication Window using php and javascript | Thinkdiff.net</h3>
    <?php if (!$fbme) { ?>
        You've to login using FB Login Button to see api calling result.
    <?php } ?>
    <p>
        <?php if ($fbme) { ?>
            <a href="<?=$logoutUrl?>">
              <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif" border="0">
            </a>
        <?php } else{ ?>
            <a href="#" onclick="login();return false;">
              <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif" border="0">
            </a>
        <?php } ?>

    </p>

    <!-- all time check if user session is valid or not -->
    <?php if ($fbme){ ?>
    <table border="0" cellspacing="3" cellpadding="3">
        <tr>
            <td>
                <!-- Data retrived from user profile are shown here -->
                <div class="box">
                    <b>User Information using Graph API</b>
                    <?php d($fbme); ?>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>User likes these movies | using graph api</b>
                     <?php d($movies); ?>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="box">
                    <b>User Information by Calling Legacy API method "users.getinfo"</b>
                    <?php d($userInfo); ?>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>FQL Query Example by calling Legacy API method "fql.query"</b>
                    <?php d($fqlResult); ?>
                </div>
            </td>
        </tr>
    </table>
    <div class="box">
        <form name="" action="<?=$config['baseurl']?>" method="post">
            <label for="tt">Status update using Graph API</label>
            <br />
            <textarea id="tt" name="tt" cols="50" rows="5">Write your status here and click 'Update My Status'</textarea>
            <br />
            <input type="submit" value="Update My Status" />
        </form>
        <?php if (isset($statusUpdate)) { ?>
            <br />
            <b style="color: red">Status Updated Successfully! Status id is <?=$statusUpdate['id']?></b>
         <?php } ?>
    </div>
    <?php } ?>

    </body>
</html>

I hope this article will help to a clear view of popup authentication. You can use my techniques to create popup authentication for twitter, linkedin, other mashup service and your own authentication system.

:)

About mahmud ahsan

Founder And Lead Programmer at iThinkdiff.net

, , , ,

86 Responses to Create Facebook PopUp Authentication Window using PHP and javascript

  1. Brian May 11, 2010 at 1:06 am #

    I had the same redirecting/refreshing problem. Not sure if it’s the server or my facebook configuration but my host is justhost.

    I hope this will work for me, thanks.

    • Erick November 4, 2010 at 1:38 am #

      I also have justhost, and I have same problem on refreshing, did it fix your problem? .

      mine just takes like 1sec while it loads, and then it loads correctly.. but it looks scary cause it repeats the webpage on frame :S..

      take a look at my website to check it out.

  2. Brian May 11, 2010 at 1:53 am #

    I just checked out the updated php-sdk and they have a better solution by refreshing the page without needing a baseurl.

  3. yadirosadi May 11, 2010 at 11:56 am #

    Hi mahmud ahsan ! thanks for sharing. join our community http://nestdev. submit and promote your article. check this , your article in there. thanks :)

  4. Dharam May 11, 2010 at 5:05 pm #

    Hi,

    I am trying to create a simple facebook connect application. Where I want to show certain contents which users can share to there facebook profile. Is that possible to do using your code above. Let me know if you have any free time to help.

    http://icymic.com/demo/fbconnect/

    The above is the URL where I am trying to do something. Inspired from ur blog to test few things at facebook :)

    Thank you.

  5. tim May 11, 2010 at 8:15 pm #

    I think you might be missing some code to close the window if the user presses cancel.

  6. mahmud ahsan May 11, 2010 at 9:19 pm #

    @tim, thanks man. I forgot that cancel button at the time of writing the post. :( I fixed my code and my demo. Please have a look again to Step 1 and Step 2.

    • Sachin December 14, 2013 at 2:09 pm #

      the demo still doesn’t work for cancel button.
      Also, if the user is already logged in to facebook, it doesn;t work.
      show the facebook home page (newsfeed) in the popup.

  7. Maury May 12, 2010 at 3:20 am #

    Thank-you very much for this. Could you do a tutorial on how to use the new auth for canvas apps – in fbml? I haven’t seen this anywhere yet, and this seems to be confusing people (plus, require_login() seems to be broken, when using the new extended permissions).

    Thanks again!

  8. ernesto May 13, 2010 at 2:25 am #

    Hello
    I had the same reflesh problem, but now with this code Is getting worse… :-(

    check here: http://apps.facebook.com/questionariouno/

    I’ve copied your new index.php
    fbmain.php and facebook.php are the same of the previous example you did.
    Any idea?

    Thank you

    • mahmud ahsan May 13, 2010 at 2:52 am #

      This code isn’t for facebook canvas or iframe base canvas app. This code is for Facebook Connect popup authentication.

    • mahmud ahsan May 13, 2010 at 2:53 am #

      And did you check the demo in this post? Did you notice that is fbconnected demo not canvas app demo.

  9. Geetha May 18, 2010 at 6:09 pm #

    Good one.
    But I have a clarification. In your demo site, if I click on the connect with Facebook, a new window is not opened.
    I could see a javascript error.

    The same happens in my website too using the above code.

    Could you please help me to find what the error could be?

    • mahmud ahsan May 18, 2010 at 6:27 pm #

      Strange!!! I just checked my demo in firefox and chrome, and its working here nicely.

      • sanalbaykus May 20, 2010 at 6:37 am #

        I tried with IE8, returns “Invalid argument” error on following line
        “newwindow=window.open(‘https://www.facebook.com/login.php?api_key=…..’,’Login by facebook’,features);”

        also tried with FF 3.5.9, permission popup window’s width growing continuously.

        • mahmud ahsan May 20, 2010 at 12:33 pm #

          I just checked my windows 7 + IE8 and there is no problem here. The popup opens nicely showing me for permissions and when I click allow it hides and redirects me to the application home page.

  10. Joe May 18, 2010 at 6:19 pm #

    Hello,

    I have a really simple question. I just create an popup authentication like you explain here. It works. But the look-and-feel of my popup window is basic, instead of your popup, wich is beautiful (with user photo, icons of request) : http://c1522252.cdn.cloudfiles.rackspacecloud.com/javascript-popup-php.jpg

    I’m just curious to know to do that ?
    Thanks !

    • mahmud ahsan May 18, 2010 at 6:30 pm #

      I think you may already approved permissions. Just remove the application from Application Setting. And try again, hopefully you’ll see the beautiful request. And remember you’ve to provide permission list so that it shows to user to approve permissions.

      • Joe May 20, 2010 at 3:15 pm #

        Hello,

        Unfortunately, when I remove all the application settings, When I reload my test page, I have always a bad looking popup with 3 steps of authorization:
        – a page for asking email authorization
        – a next page for asking to update my status
        – a third page for asking to publish

        I also remove completly the application. And same result.

        I don’t understand why, with exactly the same code (your example, just changing the api id, key, secret), I have a completly diffent render.

        Any idea ?
        Thanks

      • mahmud ahsan May 20, 2010 at 3:41 pm #

        Joe, please visit your application setting and click migration. Please be sure New Data Permission is set to enabled. I think this will solve your problem.

  11. Gnanesh May 18, 2010 at 6:21 pm #

    Hi Mahmud,

    Thanks a lot. I have got this working.

    But when i use the share() function, and give the “u” parameter as http://example.com/ignite/something.php?page=3, it gets URL encoded and it shows the link as (No Title) and hence does not get the details of the page.

    Any idea how i can tackle this.

    Thanks in Advance

  12. Joe May 21, 2010 at 7:38 pm #

    That’s it ! Thanks a lot !

  13. Nicolas May 24, 2010 at 4:55 pm #

    Hi,
    Nice hack, but I see a BIG drawback to that: your popup window is not in https, which could lead to a security issue and people not to trust you if there are use to synchronize their profile. Nowdays browsers make it CLEAR whether or not you’re working with SSL.

    Cheers,
    Nicolas.

    • mahmud ahsan May 24, 2010 at 10:18 pm #

      There is no drawback dear friend. That url is generated by facebook api library, I just passing that to the popup window. And when user provide his login information that will automatically submitted via https by that popup. Please check those carefully.

  14. Tuan Tran May 29, 2010 at 2:54 pm #

    Hi mahmud ahsan,

    Your articles about Facebook Connect is really useful.

    Anyway, I personally like PHP SDK, and refused to use JS SDK :D . And as a result, I ran into situation that I want a popup Facebook login, and so this page.

    But when I used your code with my app, it got error, which said “next is not owned by the application”. So if I remove the “next” parameter from the getLoginUrl function, it worked, but it was unable to redirect user properly.

    I think that it is due to my app settings, but I just couldn’t figure it out! Then do you have any idea about that?

  15. Aki June 4, 2010 at 7:28 am #

    Hi Mahmud,

    thank you for excellent tutorials!

    Is there a way to change the language of the authentication popup made on this article? Now it looks to be in English.

    thank you for your advice,

    regards,
    Aki

  16. Josh June 9, 2010 at 5:04 am #

    I keep receiving a ‘404 – File or directory not found’ error in the popup window when I complete your tutorial. If I print out the value of before

    newwindow=window.open(”,’Login by facebook’,features);

    I get a valid Facebook popup window address with the correct permissions. But when I click on the button trying to resolve the same address I get the 404 error. I have php 5.3.2 installed on W2k8 running IIS 7.5 and have verified through a phpinfo() window that both curl and json extensions are installed and enabled. Any help?

  17. Josh June 9, 2010 at 5:06 am #

    supposed to say – value of [?=$loginUrl?]

    newwindow=window.open(‘[?=$loginUrl?]‘,’Login by facebook’,features);

    Thanks!

  18. Mrudul June 29, 2010 at 3:45 pm #

    Hi,
    i have tried this tutorial myself…
    what i had got is almost the same as shown in the demo program but i am not able to get the email address of the user.

    please any help …??

    • mahmud ahsan July 1, 2010 at 12:08 am #

      If facebook user doesn’t approve email permission, you couldn’t retrieve his email.

  19. Christophe June 29, 2010 at 8:53 pm #

    Hi !
    I have downloaded the exact same code, just changed the parameters to my application and uploaded on my server. It works perfectly with Firefox but i can’t get connected with Chrome (5.0.375.86). After the popup refresh the main page, I am still not connected.

    Anyone had this issue?

    • mahmud ahsan July 1, 2010 at 12:07 am #

      But my code is working in my chrome browser also. So confused why its not working in your case.

  20. Jirka July 1, 2010 at 3:07 am #

    Hei, I had the same redirection problem (if I got it right). The solution was to add a SLASH to the end of the url passed in the next parameter. Without that it always ended in that loop.

    Hope this helps ;)

  21. Mrudul July 1, 2010 at 5:18 pm #

    what if i use the users.getStandardInfo() to get the emails of my friend……

    anyhow i tried to use this function but i got exception in that… some what like…

    “error_msg”: “This method call must be signed with the application secret (You are probably calling a secure method using a session secret)”,

    what it means?

  22. Mick July 1, 2010 at 9:27 pm #

    Hi,
    First of all a BIG thanks for the tutorial and tips, it works great in Firefox and Chrome but your demo is not working in I.E8. Can you please have a look? It’s very imp. if you can provide a fix for I.E8.

    Thanks
    Mick

    • Mick July 5, 2010 at 8:58 pm #

      Please provide something for I.E8, if there’s no solution is it possible to have some workaround like detecting if the browser is I.E8 and then going the normal way of authentication i.e. with no pop-ups or something? Please suggest.

      • mahmud ahsan July 5, 2010 at 10:47 pm #

        Try to use facebook normal authentications library like javascript library or php-sdk library. I use mac so currently I couldn’t test this code in IE8.

        • Mick July 6, 2010 at 5:07 am #

          Thanks mahmud but I really loved your pop-up and wanted to use it, please see if you can provide a fix for I.E8 otherwise most people won’t be able to use it. Let me know if you need any help wid testing on windows environment.

          Thanks
          Mick

  23. Mu August 3, 2010 at 4:46 pm #

    Hi Mahmud,

    thx for your great tutorial. I copied your code and just changed the params. Everything works as expected, but when i click the Logout-Button i get this exception/error from the php-sdk: “Error processing access token.”

    Did i miss something?

    Best
    Mu

    • Mu August 3, 2010 at 8:54 pm #

      Found some Infos for that:
      http://forum.developers.facebook.com/viewtopic.php?pid=240213

      You have to clear the Session before redirect to Facebook-Logout and specify the domain.

      One Question about the Cookie: Why do u set the cookie by yourself (setCookie(‘fbs_’ . “{$fbconfig['appid']}”, $strCookie);)? Is this necessary? I think the php-sdk has to set this Cookie. If i set it like you descibed it, the logout doesnt work es expected.

      Cheers
      Mu

  24. rashidul September 15, 2010 at 11:16 am #

    http://thinkdiff.net/demo/newfbconnect1/fbpopup/index.php
    DEMO NOT WORKS!

    • eshanne September 24, 2010 at 10:35 am #

      Your demo works as usual, i click and it popup and it works..

  25. harun September 27, 2010 at 10:53 am #

    how can i get dialog pop up like on this page
    http://www.facebook.com/thenorthclothing?v=app_462267815651&ref=ts

  26. Luci3n October 5, 2010 at 4:39 am #

    Check for extended perms or auth params then popup or redirect to:

    https://graph.facebook.com/oauth/authorize?
    client_id=XXX
    &redirect_uri=http://yoursitename,com/?ft_auth=1&type=user_agent&
    display=popup&scope=user_birthday,user_photos,user_hometown,user_location,publish_stream,offline_access,email,publish_stream

    is much easier if you are making a facebook app change

    display=page
    redirect_uri=http://apps.facebook.com/appname/

    works like a charm so esay for IFrame apps :-)

  27. hairul azami October 13, 2010 at 6:57 am #

    hi mahmud, nice to know your website :) very usefull contents.

    I have tried and follow your steps on this tutorial, and I see something wrong. Here are my screen shoot, maybe can help you to tell me what happen with my application sample.

    http://dremi.net/fb-popup-problem.jpg

    thank you.

    • mahmud ahsan October 13, 2010 at 1:30 pm #

      Sorry no idea about your problem. :S

  28. hairul azami October 13, 2010 at 9:01 pm #

    ok mahmud, thank you for your replay. I don’t know whan happen with this output. But I have tried the other way to create pop up facebook login. thank you for your inspiration code :)

    regard, from indonesia

  29. ShunmugaSuresh.P October 15, 2010 at 4:19 pm #

    Thanks, it’s work fine

  30. Daniel November 9, 2010 at 1:41 pm #

    Thanks – this helps a bunch. Now I need to find a way to simultaneously post to facebook and twitter with a single post from an admin dashboard : )

  31. Yanyan December 2, 2010 at 3:49 pm #

    Hi Mahmud,

    I got this error when i click the logout button

    [error] => Array
    (
    [type] => OAuthException
    [message] => Error validating access token.
    )

    I tried to clear the cache, session and cookies but still having the same problem.

    Please do advise me on what to do. thank you sooooo much.

  32. Peperrownie December 5, 2010 at 10:02 pm #

    Hi Mahmud,

    Thanks for the tutorial! It worked…but I wonder why in your demo, your popup window is not ‘blocked’, mine is ‘blocked’ “Popups were blocked from this page”

    I have to enable popup before I can see the popup window. Any suggestions how can I avoid this or why is this happening?

    Thank you so much for your help!

    • mahmud ahsan December 7, 2010 at 4:08 pm #

      Emm i think if user click and popup open then browser doesn’t block it, otherwise if you auto open a popup then browser first block it until you approve.

  33. Aman January 13, 2011 at 7:37 pm #

    Cant open On IE

  34. Fred January 15, 2011 at 1:58 am #

    Hi Mahmud,

    Wow – what a great tutorial. Got it all working but now comes the task of integrating it with my current registration/login php module…

    My main question is how does the app know this is a first time FB registration and therefore must ad the record to the MySql DB vs. it being a return visitor who’s already registered and simply needs to login FB.

    Can both instances go to separate urls after the popup?

    First time registration would go to register.php
    Return visitors would go to login.php

    For instance.

    I look forward to your thoughts!

    Thanks~

    • mahmud ahsan January 17, 2011 at 11:22 pm #

      Your question sounds confusing, normally you can store user’s uid in your database.
      And in the facebook developer application setting you’ll find

      Post-Authorize Callback URL field. Fill this with a valid url. Facebook pings this URL when a user first authorizes your app

  35. Julesjanes February 14, 2011 at 3:35 pm #

    Hi Mahmud,
    Great work!
    Is it possible after uploading a photo in user’s gallery it does not appear automatic on the Wall.But only after user allows it?

  36. Edwin March 2, 2011 at 10:00 pm #

    Gracias por el tutorial, esta en ingles pero me dio mas ideas para mejorar mi aplicacion.

  37. Joan Ballester March 8, 2011 at 1:02 am #

    Hi, in my case, I see the next bug:
    If I click on connect, perfect.
    Then, Logout, perfect again.
    But if I click again in Connect, the popup asks me for my login and pass in facebook (ok), then send… and redirects in the same window popup…
    I supose, the idea is refresh the main window of the application, and not the window popup.

    Any ideas?

  38. zeeshan March 11, 2011 at 4:09 pm #

    hello all, nice article Mahmud but i get an error when i clicked to “connect to facebook” button the window popup appear with error Invalid Argument
    Given URL is not allowed by the Application configuration. and if i already connect to facebook than pop up says API Error Code: 191
    API Error Description: The specified URL is not owned by the application
    Error Message: redirect_uri is not owned by the application. you can check it here http://cpantry.com/match/

  39. DD May 2, 2011 at 3:23 am #

    Thanks for the script! How do you pass the uid from the JS to php?

  40. djd May 18, 2011 at 4:23 pm #

    dude you are awesome. I searched everywhere for a proper tutorial for fb authentication for hours, this is the only one which seems to work :)

  41. C June 1, 2011 at 12:52 am #

    hi, thanks for the tutorial, it works great except that somehow my buttons are hidden in the js popup, any idea how to set canvas size without using the FB javascript sdk? thanks! (the demo has the same problem btw, buttons not visible in the popup)

  42. Khawer Zeshan June 24, 2011 at 5:10 pm #

    Hi excellent tutorial … but i am having a problem when authentication completed pop up doesn’t close and the page refreshes inside the pop up … i want the information on the page from where it was called e.g index.php …. i have exact copied ur code … please tell me the solution

  43. Kashif June 28, 2011 at 12:26 pm #

    Hi mahmud ahsan

    I don’t want user authentication popup every time. I have an email and password. So i want to get session value by simply passing it through. Any Idea how can i do this ?

    Thanks in advance,
    Kashif

  44. Rifas September 15, 2011 at 5:57 am #

    Hey can u send me the source of this java+php thng.. plsssssssss..mail id mohdrifu@gmail.com

  45. Swapnil September 20, 2011 at 1:03 pm #

    Hi, I am using Ruby On rails for web server and Rhodes for mobile application.
    I am able to login to facebook and post the data on wall of user using Graph api and Oauth2.
    Issue I do have is when first user sign into facebook and authenticates app then for each user facebook page is not shown and all posts are posted on first users facebook profile.
    So i think user is not getting sign out of facebook or cookies are being stored so not allowing other users to get authenticated.
    For twitter, things work fine, each user is asked for authentication and posts posted on respective twitter accounts.
    I am not getting how to clear out facebook cookies stored locally and logout user from facebook.
    Please help me about this.

    • mahmud ahsan September 20, 2011 at 4:55 pm #

      Unfortunately neither I worked on Ruby or Rhodes. Please search google may be you’ll get some useful links.

  46. hirenbg89 October 12, 2011 at 12:52 pm #

    hi mahmud, thanks for the gtreat tutorial. can i know which version of php sdk you are using here..?? thnks

    • mahmud ahsan October 14, 2011 at 5:53 pm #

      This is old PHP sdk.

  47. Larry December 11, 2011 at 8:29 am #

    Hey, man! Congrats for the great blog! It has been a really useful resource for me to learn fb app building.

    I am trying to create a tab that uses the popup dialog, but for a reason I can’t make the popup window close after I approve. Just wondering what can be wrong.

    If you have any idea please let me know (the link is https://www.facebook.com/pages/Larrytest/326326387781?sk=app_143425715753379)

    Thanks a lot for your time man!

    Keep great job!

  48. I used to be suggested this website through my cousin. I am not certain whether or not this post is written via him as no one else understand such precise about my difficulty. You’re incredible! Thank you!

  49. vietnam June 21, 2012 at 10:42 am #

    i don’t download source code of you ,please send for me to email : mr.qthien@gmail.com thank much

  50. Dane July 23, 2012 at 12:38 pm #

    crap! not working!

  51. Blog Jaka Sifra July 28, 2012 at 6:03 pm #

    thx for your great tutorial

  52. Salman Raza October 7, 2012 at 3:08 pm #

    Hi, Just wanted to ask that can i use this code, modify it and put it on my website ? Is there any licensing issues ? and it is ethical to do so ?

  53. arul ananth October 29, 2012 at 3:39 pm #

    after login your demo application cannot work .its work before 10 days,now this application have the problem.

  54. jamspidy November 8, 2012 at 12:07 pm #

    I encounter this error message when trying to login in facebook
    Error Summary
    HTTP Error 400.0 – Bad Request
    ASP.NET detected invalid characters in the URL.

  55. avadhraj December 8, 2012 at 5:23 pm #

    hi
    myself avadhraj please give me the ideas
    i want to do user login facebook from my website and display the total friend in my account with name and when the user click on that name the display the all the photo album is uploaded by that user if any API Plugin tell me . please help me as soon as possible

    thank u

  56. Ganesh July 12, 2013 at 2:45 pm #

    Good article! I have a doubt. does this ‘window.open’ approach works if popups are blocked in browser? I tried my Firefox said it blocked the popup :(

    Regards,
    Ganesh.

  57. minecraft July 22, 2013 at 5:52 am #

    A) Using this site you understand that no part of the Minecraft game is actually served from our servers and that you are playing the official game
    streamed directly from minecraft.net.

  58. jigar February 4, 2014 at 1:12 am #

    hi,
    i can not understand how login/logout works at your side.
    on my side when i have download and try to use it on my local host it generates lots of error and prints some array structure.i don’t know what exactly it is.and also i can’t get latest php sdk on your given link.
    I just want a login logout like your demo link and when user clock on it his id,birthdate and name will be stored in database.
    please help me. i tried lots of thing.i have already one login but in that i couldn’t stored data in database.