Graph API & IFrame Base Facebook Application Development

FacebookFacebook is one of the top social networking site and its easy to develop facebook application. You can also easily integrate facebook features via facebook connect into your site. But it may happen that you want to develop facebook application that will run within facebook site. If this is the case, then this is the right article for you to start.

In this article I discussed all the basics and techniques you need to develop iframe base facebook application.

You’ll learn from this article:

  1. Setup IFrame Application
  2. Facebook Authentication for Iframe Application
  3. Setting extended permission for more information
  4. How to set links
  5. Form Submission technique and getting Data
  6. JQuery – how to use javascript and javascript library
  7. Graph api using php
  8. Stream Publish (wall post)
  9. Status Update via php api
  10. Status Update via javascript api
  11. Invitation Feature
  12. Iframe Resizing

Before proceeding checkout the demo & Download Code

Demo: http://apps.facebook.com/thinkdiffdemo/ (this application now runs PHP SDK 3.0 base code)
Download Old Code PHP SDK 2.2
PHP SDK 3.0 Base Updated Code

UPDATED Tutorial and Code

If you’re first time developer then read the full post and then the updated post , otherwise skip this post and just go to the updated post.

http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development-php-sdk-3-0/

Recommended Reading

  1. http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
  2. http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/

1. Setup IFrame Application

First visit http://www.facebook.com/developers and setup your facebook application. Set your project server path in Canvas Callback Url, set a canvas page url name, set render method to IFrame, set iframe size Resizable.

facebook app setup screen 1

Set Connect URL to your project server url also

facebook app setup screen 2

Now click save changes . So you just created a new facebook app.

Now download my code and upload all the files to your server’s project dir.

facebook.php is the php-sdk library. Now update configuration of fbmain.php. Copy paste your application’s appid, api key, secret key in $fbconfig. And also set $fbconfig baseUrl and appBaseUrl .

//facebook application
    $fbconfig['appid' ] = "";
    $fbconfig['api'   ] = "";
    $fbconfig['secret'] = "";

    $fbconfig['baseUrl']    =   ""; //http://thinkdiff.net/demo/newfbconnect1/ifram
    $fbconfig['appBaseUrl'] =   ""; //http://apps.facebook.com/thinkdiffdemo

In the template.php you’ll see I load facebook javascript library. Its mandatory to render xfbml tags in your application and also some facebook tasks via javascript.

<div id="fb-root"></div>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
     <script type="text/javascript">
       FB.init({
         appId  : '<?=$fbconfig['appid']?>',
         status : true, // check login status
         cookie : true, // enable cookies to allow the server to access the session
         xfbml  : true  // parse XFBML
       });
     </script>

So the application setup is complete.

2. Facebook Authentication for Iframe Application

fbmain.php file is used for facebook authentication also. Here look at this part

//Facebook Authentication part
    $session = $facebook->getSession();
    $loginUrl = $facebook->getLoginUrl(
            array(
            'canvas'    => 1,
            'fbconnect' => 0,
            'req_perms' => 'email,publish_stream,status_update,user_birthday, user_location,user_work_history'
            )
    );

    $fbme = null;

    if (!$session) {
        echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
        exit;
    }
    else {
        try {
            $uid      =   $facebook->getUser();
            $fbme     =   $facebook->api('/me');

        } catch (FacebookApiException $e) {
            echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
            exit;
        }
    }

Look we pass an array of configuration in getLoginUrl().  canvas=1 as our app is iframe app.

If we don’t find a valid session or session key is expired, we redirect user to the facebook login page generated by getLoginUrl() function via javascript code top.location.href.

3. Setting extended permission for more information

You couldn’t get some information until user approve your application via extended permission. So look in our above code we provided these extended permissions

‘req_perms’ => ‘email,publish_stream,status_update,user_birthday, user_location,user_work_history’

Checkout extended permission list from here.

4. How to set links

In my application you’ll see menu links like Home, Invite . If you see the code for template.php you’ll see below codes at the bottom.

<a href="<?=$fbconfig['appBaseUrl']?>" target="_top">Home</a> |
    <a href="<?=$fbconfig['appBaseUrl']?>/index.php?page=invite.php" target="_top">Invite</a>

The important thing is that you must provide target=”_top” in all links for your iframe app. Otherwise when you’ll click the link the full facebook will load in the iframe.

5. Form Submission technique and getting Data

One of the most important thing is form submission. If your application have any form then you have to provide action url as your application’s callbackurl. Don’t use facebook application url otherwise you’ll not get form data. And also again use target=”_top” within form tag.

<form name="fs" action="http://yoursite.com/yourfbapplication/form.php" target="_top" method="POST">
Your Name: <input name="name" value="" />
<input name="submit" type="submit" value="Submit" />
</form>

And after getting data redirect user to the app url.
form.php

if (isset($_REQUEST['submit'])){
    //retrieve form data here
    $name = $_REQUEST['name'];
    //save data to database or do other tasks
}

//now redirect user
header ("Location: http://apps.facebook.com/yourapplicationurl");
exit;

6. JQuery – how to use javascript and javascript library

When we develop fbml canvas base facebook application, we only can use partial and modified javascript named FBJS. But in iframe application development you could easily use normal javascript and any javascript library like jquery.

jquery-menu

Look the menu in my application. To create this menu here I coded.

In template.php I first load the jquery javascript library and ui library.

 <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script></pre>

Then I call the jquery function after the page fully loaded. And it will find the div named ‘tabs’ and make them a nice tabbed menu.

<script type="text/javascript">
            $(document).ready(function () {
                $("#tabs").tabs();
            });
</script>

And in home.php view file I coded for tab.

<div id="tabs">
    <ul>
        <li><a href="#fragment-1"><span>User Information</span></a></li>
        <li><a href="#fragment-2"><span>FQL Query</span></a></li>
    </ul>
    <div id="fragment-1">
        <img src="http://graph.facebook.com/<?=$uid?>/picture" alt="user photo" />
        <br />
        <div style="height: 400px; overflow: auto">
            <?php d($fbme); ?>
        </div>
    </div>
    <div id="fragment-2">
        <div style="height: 400px; overflow: auto">
        <?php
            echo "FQL QUERY: " . $fql;
            d($fqlResult);
        ?>
        </div>
    </div>

You can also easily use jquery ajax function to do ajax tasks. So its really amazing to use javascript library in your facebook application.

7. Graph api using php

Calling graph api using php sdk its very easy. In my previous article check how to call graph api using php. In fbmain.php you’ll see I called graph api.

$fbme     =   $facebook->api('/me');

8. Stream Publish (wall post)

Its very easy to publish stream via facebook javascript sdk. You’ll see in template.php I loaded facebook javascript library. And you’ll see below code there

    function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
        FB.ui(
        {
            method: 'stream.publish',
            message: '',
            attachment: {
                name: name,
                caption: '',
                description: (description),
                href: hrefLink
            },
            action_links: [
                { text: hrefTitle, href: hrefLink }
            ],
            user_prompt_message: userPrompt
        },
        function(response) {

        });
    }
    function publishStream(){
        streamPublish("Stream Publish", 'Thinkdiff.net is AWESOME. I just learned how to develop Iframe+Jquery+Ajax base facebook application development. ', 'Checkout the Tutorial', 'http://wp.me/pr3EW-sv', "Demo Facebook Application Tutorial");
    }

In home.php view file you’ll see I just call the publishStream() method to show the stream box.

<div id="fragment-3">
        <a href="#" onclick="publishStream(); return false;">Click Here To Show A DEMO Stream Publish Box</a>
    </div>

Visit facebook official library documentation to know more about stream publish.

9. Status Update via JQuery Ajax and php api

In the template.php you’ll see I created a javascript function. This function used jquery ajax functionality to send request to server and load.

    function updateStatus(){
        var status  =   document.getElementById('status').value;

        $.ajax({
            type: "POST",
            url: "<?=$fbconfig['baseUrl']?>/ajax.php",
            data: "status=" + status,
            success: function(msg){
                alert(msg);
            },
            error: function(msg){
                alert(msg);
            }
        });
    }

In the home.php you’ll see I’ve a textarea where user will write something and if click the button it will call updateStatus() javascript function to pass value to server.

<div id="fragment-4">
        <form name="statusUpdate" action="" method="">
            <textarea name="status" id="status" rows="4" cols="50"></textarea>
            <input type="button" onclick="updateStatus(); return false;" value="Write Something And Click Me" />
        </form>
    </div>

And in ajax.php you’ll see. Here user’s status will update via facebook api.

<?php
    include_once "fbmain.php";

    if ($fbme){
        //update user's status using graph api
        if (isset($_REQUEST['status'])) {
            try {
                $status       = htmlentities($_REQUEST['status'], ENT_QUOTES);
                $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> $status, 'cb' => ''));
            } catch (FacebookApiException $e) {
                d($e);
            }
            echo "Status Update Successfull. ";
            exit;
        }
    }
?>

10. Status Update via javascript api

In template.php you’ll see a javascript function. Where I used facebook javascript api to update status.

    function updateStatusViaJavascriptAPICalling(){
        var status  =   document.getElementById('status').value;
        FB.api('/me/feed', 'post', { message: status }, function(response) {
            if (!response || response.error) {
                alert('Error occured');
            } else {
                alert('Status updated Successfully');
            }
        });
    }

In home.php you’ll see I call this updateStatusViaJavascriptAPICalling() method to update status.

    <input type="button" onclick="updateStatusViaJavascriptAPICalling(); return false;" value="Update Status via Facebook Javascript Library" />

11. Invitation Feature

Checkout the invite.php code

<?php
     include_once "fbmain.php";
    if (isset($_REQUEST['ids'])){
        echo "Invitation Successfully Sent";
        echo '<pre>';
        print_r($_REQUEST);
        echo '</pre>';
        echo "<b>If you need to save these user ids then save these to database <br />then redirect user to the apps.facebook.com/yourapp url</b>";
        $string = "<script type='text/javascript'>top.location.href='{$fbconfig['appBaseUrl']}'; </script>";
        echo "Use the following javascript code to redirect user <br />";
        echo htmlentities($string, ENT_QUOTES);
    }
    else {
?>
<fb:serverFbml style="width: 500px;">
    <script type="text/fbml">
      <fb:fbml>
          <fb:request-form
                    action="<?=$fbconfig['baseUrl']?>/invite.php"
                    target="_top"
                    method="POST"
                    invite="true"
                    type="Demo Application | Thinkdiff.net"
                    content="Checkout this demo application and learn iframe base facebook application development. <fb:req-choice url='<?=$fbconfig['appBaseUrl']?>' label='Accept' />"
                    >

                    <fb:multi-friend-selector
                    showborder="false"
                    actiontext="Checkout this demo application and learn iframe base facebook application development">
        </fb:request-form>
      </fb:fbml>
    </script>
  </fb:serverFbml>
<?php } ?>

Read the comments within code. remember if you want the users ids whom a user sent invitation then don’t forget to use callback url not facebook app url. And after getting invited user ids redirect user to the facebook app url.

12. Iframe Resizing

Sometimes you may need to resize your iframe app in runtime. Then use the following code to set iframe size

<script type="text/javascript">
    var obj =   new Object;
    obj.width=900;
    obj.height=1800;
    FB.Canvas.setSize(obj);
</script>

I hope this article has given you a clear view to developing iframe base facebook application. Don’t forget to checkout the demo application and to see the codes.

Reference:

Comments are closed now.

About mahmud ahsan

Founder And Lead Programmer at iThinkdiff.net

, , , , , ,

386 Responses to Graph API & IFrame Base Facebook Application Development

  1. Nivas Sivanadiyan May 28, 2010 at 8:41 pm #

    Very nice, Useful …

    • Rami Cohen June 2, 2010 at 3:04 pm #

      Thanks a million.
      Finally a good and useful example.

      ~Rami

      • mahmud ahsan June 3, 2010 at 5:04 am #

        Glad to know this helps you.

  2. shaon May 28, 2010 at 8:53 pm #

    great work. I was finding such thing for last couple of days

  3. kushagra gour May 28, 2010 at 10:48 pm #

    Hi…a really awesome and much needed tutorial.
    One thing..i noticed that the “makeRequest()” function in your facebook.php file is somewhat different. specifically this part :

    if ($result === false) {
          $e = new FacebookApiException(array(
            'error_code' => curl_errno($ch),
            'error'      => array(
              'message' => curl_error($ch),
              'type'    => 'CurlException',
            ),
          ));
          curl_close($ch);
          throw $e;
        }
    

    Can u plz exlpain its use ?

    thanx again

    • mahmud ahsan May 28, 2010 at 11:14 pm #

      I don’t change anything of that library. May be my php-sdk library is a bit older. So download the latest library from here http://github.com/facebook/php-sdk/ and replace the facebook.php by the latest library.

  4. kushagra gour May 29, 2010 at 1:05 am #

    I tries running your example as it is..but it didnt work :(

    http://apps.facebook.com/chang_app/
    It keeps on redirecting between 2 urls.

    Also are there some more settings needed to use the JS-sdk ?
    I hope the settings u mentioned in your post are enough.

    plz help..i’ve been trying to run my app since 5 dayz now :P

    thanx

    • vibhu August 9, 2010 at 8:39 pm #

      I am also facing the same problem.

    • vibhu August 9, 2010 at 8:50 pm #

      If you are on ubuntu this can be fixed by installing certificates
      Just do
      sudo apt-get install ca-certificates

  5. zach young May 29, 2010 at 4:09 am #

    I’ve had no problems setting up the sweet example you gave… but I’m unable to get the Invite button to behave properly… simply redirects me to the “home” section even though the url contains the “appName/index.php?page=invite.php” is there something magical I’m missing?

    • mahmud ahsan May 29, 2010 at 4:37 am #

      No there is no magic. I provided the full source code please try again carefully.

      • zach young May 29, 2010 at 5:59 am #

        I did finally get it all working, but I had to do this in the index.php

        $page = $_GET['page'];

        above this:

        //set page to include default is home.php
        $page = isset($page) ? $page : “home.php”;

        I don’t know if I’ve just messed something up in the implementation or what, but that get seems to fix it perfectly… Still the ABSOLUTE BEST tutorial out there, thanks a million! :)

        • mahmud ahsan May 29, 2010 at 10:58 am #

          Actually I found in the index.php (within .zip file) this line code is missed.

          //set page to include default is home.php
              $page   =   isset($_REQUEST['page']) ? isset($_REQUEST['page']) : "home.php";
              include_once "template.php";
          

          I fixed it. And thanks to you for informing me.

          • byrtman June 13, 2010 at 10:48 am #

            I don’t think this fix will work either. What you’re saying here is if the page is set, then assign $page to true, not the page url. I changed it by removing the isset part for the true condition.

          • Danny September 4, 2010 at 9:57 am #

            Thanks for the great tutorial. The Invite code doesn’t work for me yet. The invite window seems to open porperly but once the invite is complete or you click skip, it takes you to a blank page.

            I tried your http://apps.facebook.com/thinkdiffdemo/
            demo and it does the same thing.

            Thanks for all the hard work.

  6. goldfuz3 May 31, 2010 at 2:25 am #

    Can you please explain to me the difference between baseUrl and appBaseUrl?

    Thanks!

    • mahmud ahsan May 31, 2010 at 12:30 pm #

      baseUrl = Your server url where you’ll host your project.
      appBaseUrl = facebook application url that grab data from baseUrl

  7. kevin May 31, 2010 at 7:16 am #

    you’re the gun!!!!!!! you have no ideas how much miseries I have went through to set up a “working” facebook app using facebook’s official outdated/updated/messed up documentations…. Now, let me play with your script :)

  8. Benson May 31, 2010 at 10:55 am #

    Help … I still don’t know how to do : Facebook Authentication for Iframe Application.

    After I modify your code will face problem.

  9. BEN May 31, 2010 at 4:17 pm #

    i try to download your code but :

    Not Found

    Sorry, but you are looking for something that is not here.

    • mahmud ahsan May 31, 2010 at 5:44 pm #

      Which link you tried. Mention please. I just checked and found download link is working.

  10. IlexN June 1, 2010 at 11:31 am #

    I used the IE7 play with your application (http://apps.facebook.com/thinkdiffdemo/)

    before I login to facebook, and go to the application, it works.

    after logout, i test again.

    now i login the facebook, than go to the application again, and got 404 error.

  11. marcos cabrera June 1, 2010 at 11:38 am #
    try {
                $uid      =   $facebook->getUser();
                $fbme     =   $facebook->api('/me');
    
            } catch (FacebookApiException $e) {
                echo "alert('que pasa aqui ?');";
                //echo "top.location.href = '$loginUrl';";
                d($e);
                exit;
            }
    

    this error is the result the api call

    anyone can help me ?
    anyone more with this problem ?

    FacebookApiException Object
    (
        [result:protected] => Array
            (
                [error_code] => 60
                [error] => Array
                    (
                        [message] => SSL certificate problem, verify that the CA cert is OK. Details:
    error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
                        [type] => CurlException
                    )
    
            )
    
        [message:protected] => SSL certificate problem, verify that the CA cert is OK. Details:
    error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
        [string:private] => 
        [code language=":protected"][/code][/code] => 60
        [file:protected] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\facebook.php
        [line:protected] => 511
        [trace:private] => Array
            (
                [0] => Array
                    (
                        [file] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\facebook.php
                        [line] => 487
                        [function] => makeRequest
                        [class] => Facebook
                        [type] => ->
                        [args] => Array
                            (
                                [0] => https://graph.facebook.com/me
                                [1] => Array
                                    (
                                        [method] => GET
                                        [access_token] => 130893886924846|2.tyevwxpifiXFyZ81asJ98w__.3600.1275372000-100001090805271|QjB6hu7VTQeP-EKhfzY539zBPsw.
                                    )
    
                            )
    
                    )
    
                [1] => Array
                    (
                        [file] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\facebook.php
                        [line] => 449
                        [function] => _oauthRequest
                        [class] => Facebook
                        [type] => ->
                        [args] => Array
                            (
                                [0] => https://graph.facebook.com/me
                                [1] => Array
                                    (
                                        [method] => GET
                                    )
    
                            )
    
                    )
    
                [2] => Array
                    (
                        [function] => _graph
                        [class] => Facebook
                        [type] => ->
                        [args] => Array
                            (
                                [0] => /me
                            )
    
                    )
    
                [3] => Array
                    (
                        [file] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\facebook.php
                        [line] => 402
                        [function] => call_user_func_array
                        [args] => Array
                            (
                                [0] => Array
                                    (
                                        [0] => Facebook Object
                                            (
                                                [appId:protected] => 130893886924846
                                                [apiSecret:protected] => 3c7ea537d8f5fe05f64cce6e3cda19f6
                                                [session:protected] => Array
                                                    (
                                                        [uid] => 100001090805271
                                                        [session_key] => 2.tyevwxpifiXFyZ81asJ98w__.3600.1275372000-100001090805271
                                                        [secret] => jHFMiJ81V5tbbu1tR6ntXQ__
                                                        [expires] => 1275372000
                                                        [access_token] => 130893886924846|2.tyevwxpifiXFyZ81asJ98w__.3600.1275372000-100001090805271|QjB6hu7VTQeP-EKhfzY539zBPsw.
                                                        [sig] => 867f79ae89dfaf9e2f2ad3f86e1a6997
                                                    )
    
                                                [sessionLoaded:protected] => 1
                                                [cookieSupport:protected] => 1
                                                [baseDomain:protected] => 
                                            )
    
                                        [1] => _graph
                                    )
    
                                [1] => Array
                                    (
                                        [0] => /me
                                    )
    
                            )
    
                    )
    
                [4] => Array
                    (
                        [file] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\fbmain.php
                        [line] => 50
                        [function] => api
                        [class] => Facebook
                        [type] => ->
                        [args] => Array
                            (
                                [0] => /me
                            )
    
                    )
    
                [5] => Array
                    (
                        [file] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\index.php
                        [line] => 2
                        [args] => Array
                            (
                                [0] => C:\inetpub\vhosts\ctz.com.mx\httpdocs\netcetera_magazine\fbmain.php
                            )
    
                        [function] => include_once
                    )
    
            )
    )
    
  12. elba June 1, 2010 at 8:29 pm #

    It’s the best up to date tutorial ever.
    Thanks for sharing the code.
    Could you point me to the right direction to only display the logged in user name under the user information tab?
    I wanted to use xfbml fb:name under the picture but it returns zero – it seems that it requires a login?
    Thanks.

    • mahmud ahsan June 2, 2010 at 11:32 am #

      To render XFBML tag correctly first check that whether you loaded the javascript library correctly or not. Then code is simple

      <?php
      $uid = $facebook->fbme['id'];
      ?>
      <fb:name uid="<?=$uid?>" useyou="false"></fb:name>
      
      • jon June 15, 2010 at 5:12 pm #

        could you please give as an example of how to do that?
        really really thanks

  13. babyking June 2, 2010 at 2:44 pm #

    great tutorial… help me alot. Is that posible to add profile tab in iframe application?

    • mahmud ahsan June 3, 2010 at 5:05 am #

      Ofcourse you’ll add profile tab in iframe application. But remember iframe is not supported within profile tab and there is a different between iframe base canvas app and profile tab/page tab application. Checkout facebook official documentation for more info.

  14. Stijn June 2, 2010 at 11:07 pm #

    When I run the application I have this error:

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: next is not owned by the application.

    The only things I’ve changed:

    //facebook application
    //set facebook application id, secret key and api key here
    $fbconfig['appid' ] = “**”;
    $fbconfig['api' ] = “**”;
    $fbconfig['secret'] = “**”;

    //set application urls here
    $fbconfig['baseUrl'] = “**1**”;
    $fbconfig['appBaseUrl'] = “**”;

    Canvas Callback URL: **1**

    • mahmud ahsan June 3, 2010 at 5:03 am #

      Research man, do some research, you’ll solve it yourself. I’ve not enough time to solve everyone’s problems.

    • sneakyimp June 3, 2010 at 5:20 am #

      I’ve seen error 100 when the facebook server does not have access to a callback URL. For instance, you can use a 192.168.1.1 server address for any of your callback urls because facebook’s server can’t access your local server.

    • Adam Fordham June 7, 2010 at 4:17 pm #

      Make sure you app id, api key, and secret code are correct. And also make sure you base url, and app base url match what facebook has or you will get an error. I installed this app and edited per instructions with no problems. Also make sure you hosting provider is using php 5. Mine is using php 4 and i got an error right away but there is and easy fix for that also just by adding a simple .htaccess file with the content AddType x-mapp-php5 .php this will work as long as your webhost is using apache. Good luck hope everything works out for you.

  15. sneakyimp June 3, 2010 at 3:24 am #

    In section 5, you propose an inherently insecure method of handling form posts. The form doesn’t send any facebook credentials to the form-handling code which makes no effort to validate that the user is who they say they are.

    • mahmud ahsan June 3, 2010 at 5:01 am #

      Facebook will auto add some fields along with form data that you can capture and validate in the server. For simplicity I don’t mention those code. Those are up to the developers and I assume the developers have good knowledge of security like you.

      • sneakyimp June 3, 2010 at 5:15 am #

        Are you saying that my forms will be automatically modified? I don’t see how that will happen if my form is displayed in an iFrame unless I am linking some javascript from Facebook. Perhaps you could clarify? I just don’t see how this form propagates any facebook credentials at all:

        <form name="fs"  action="http://yoursite.com/yourfbapplication/form.php"  target="_top"  method="POST">
          Your Name: <input name="name" value="" />
          <input name="submit" type="submit" value="Submit" />
        </form>
        

        Nor do I see how this code checks for any of these credentials:

        if (isset($_REQUEST['submit'])){
        	    //retrieve form data here
        	    $name = $_REQUEST['name'];
        	    //save data to database or do other tasks
        }
        	 
        //now redirect user
        header ("Location: http://apps.facebook.com/yourapplicationurl");
        exit;
        
  16. Ron June 3, 2010 at 8:12 am #

    the download the code link is not working.

    http://thinkdiff.net/facebook/demo/newfbconnect1/iframe/iframe_base_facebook_app_by_mahmud.zip

    not found.

  17. Benson June 3, 2010 at 10:59 am #

    Thank you … all you code work so well …

  18. ilker June 5, 2010 at 4:16 am #

    I was trying same process with .net but no success.
    Is it possible all about login url.

    I am trying that url http://www.facebook.com/login.php?api_key={0}&v=1.0&canvas.

    When I logged in it redirect me to the canvas url but I could not use for example FB.getSession(). it returns undefined.

    Thanks.

  19. Sparrow June 6, 2010 at 12:45 am #

    Great article, helped me a lot. I had a asking for you..is there any way to set a default minimum height for fb app iframe and if content is longer than the default height, then it will appear scrollbar, but the iframe height wont be change. if this is possible then will be great and if you tell me how if possible then it would be super great. Thank you any way…

  20. nasyarobby June 6, 2010 at 12:49 pm #

    Hi there… I read your article since I couldnt find any article that spesific like yours. I’ve encountered sertificate security warning because my apps connected to https protocol. Can you help to get rid of this message so new user is not affraid because they think my apps is not secured?
    Big thanks.

    • mahmud ahsan June 7, 2010 at 1:45 am #

      If you use https protocol as callback url then you should use https as the javascript sdk loading time.

      <script type="text/javascript"  src="https://connect.facebook.net/en_US/all.js"></script>
      
  21. Adam Fordham June 7, 2010 at 4:11 pm #

    Thank you very much great article. I have been looking for examples for about a week now. Every article I have found has been based around php-sdk 1. Finally I have a working example to have and idea how everything works. You have been very helpful thank you again

  22. Henry June 8, 2010 at 11:03 am #

    when I try to go http://apps.facebook.com/thinkdiffdemo ,
    my IE shown me the error :There is a problem with this website’s security certificate. Anyone have the idea?

  23. eka June 8, 2010 at 11:18 am #

    hey there..

    i always get NULL value on the
    $fbme = $facebook->api(‘/me’);

    var_dump($fbme);

    and for note

    using var_dump($facebook->getSession()) get result like this.

    array(6) { ["access_token"]=> string(103) “118750864833609|2.lZHyHkLpq_df4JmEQQuXFw__.3600.1275976800-100001190678474|Pc-hWFzNvfUkmBEMROa33ZG1JH0.” ["expires"]=> string(10) “1275976800″ ["secret"]=> string(24) “rVjTPaBPphTngm_aznQ7TQ__” ["session_key"]=> string(58) “2.lZHyHkLpq_df4JmEQQuXFw__.3600.1275976800-100001190678474″ ["sig"]=> string(32) “a78f5f81ca457cf55db323a5319d5141″ ["uid"]=> string(15) “100001190678474″ }

    anyone can help me about this. ?

  24. Henry June 8, 2010 at 11:37 am #

    I solved the problem , here is the code

    if (!$session) {
    		$newString = str_replace("https","http",$loginUrl);
            echo "top.location.href = '$newString';";
            exit;
        }
    
    • Dave Shaw August 30, 2010 at 1:16 am #

      Thanks for this post, it ended my infinite loop while running the example under facebook.

  25. Javed Nazir June 8, 2010 at 5:51 pm #

    Hi Mahmud,
    thank you for the demo app code. I have set it up and it is working fine. But now I want to run this app as part of a fan page.

    I looked at your other post, and added the tab name and tab URL. Tab Name: Projectx, tab url: apps.facsbook.com/projectx/index.php (this index.php is the same file, which I downloaded as part of your demo code).
    Will this work? as a fan page app? How to make this work….
    thnks in advance…. Javed

  26. Stas June 9, 2010 at 8:07 pm #

    check also free PHP IDE Codelobster PHP Edition with special plug-in for Facebook Application development.

  27. ccarrasco June 10, 2010 at 12:26 am #

    mahmud thanks for the tutorial :)
    but, how can i use fbml in an iframe app?
    i need to use this in my app:
    thanks!

    • mahmud ahsan June 10, 2010 at 12:36 am #

      you can use xfbml please check the official documentation. You could also use some fbml tags using serverFBML system. But normally most of the fbml tags will not work in iframe app.

      • ccarrasco June 10, 2010 at 12:37 am #

        Thanks ! :D

      • ccarrasco June 10, 2010 at 5:09 am #

        i was alredy add the code ‘ ‘ but is not work, this is the error :
        API Error Code: 200
        API Error Description: Permissions error
        Error Message: Permissions error :(

  28. danbe June 10, 2010 at 2:59 pm #

    Thank you Mahmud you are more than ahsan!
    Did any one implemented your excellent tutorial into java?

    I have a J2EE application which I want to embed into facebook, as an iframe. I must admit I am having problems with it.

    Thank you again,
    Dan

  29. chumzz June 11, 2010 at 2:45 am #

    Thanks a million!! I have been looking for a proper tutorial to get my feet wet. Thanks again!

  30. miss geje June 12, 2010 at 9:00 pm #

    I need help how you can take the quiz answers from each respondent that we make on facebook ….. I beg help for my research .. It links my quiz application http://apps.facebook.com/etika-berlalu-biaiij/?start=1&target=home&ref=mf

    thank before

  31. golow June 13, 2010 at 4:37 pm #

    Thank you soooo much :D

  32. sisira June 14, 2010 at 1:34 pm #

    thanks this post.
    but this works only facebook profile only.
    but when i create facebook page.
    then i tried to connect with facebook page user name nad password.
    but itsnt working.
    pls help me.

  33. ilk June 14, 2010 at 10:31 pm #

    Hi,

    I stop working when I activate new “New Data Permissions” in migrations tab in application edit page.

    Previously facebook call my app with following parameters:

    demo/newfbconnect1/iframe/?ref=appd_my_recent&
    fa=1&
    fb_sig_in_iframe=1&
    fb_sig_iframe_key=aab3238922bcc25a6f606eb525ffdc56&
    fb_sig_locale=en_EN&
    fb_sig_in_new_facebook=1&
    fb_sig_time=1276514022.3667&
    fb_sig_added=1&
    fb_sig_profile_update_time=1235004624&
    fb_sig_expires=1276520400&….

    and now It calls with :

    ?session={“uid”:”654545454″, “session_key”:”2.5XJffUjKrFr3m_iXKUWZiQ__.3600.1276534800-654545454″,”secret”:”xFsZRDWfrC8hjIDP0sbv3Q__”, “expires”:1276534800,” access_token”:”112478858780817|2.5XJffUjKrFr3m_iXBUCZiQ__.3600

    Is it normal ? and How can I understant user is added my app (previously : fb_sig_added=1 parameter)

    Thanks

  34. Michael Gaigg June 15, 2010 at 6:18 am #

    Hi,

    what’s the difference between the “Canvas Callback URL” and the “Connect URL”? I see that for the canvas callback url you added /iframe/ – is the iframe directory the ‘server project dir’? If so, what goes into the connect url dir?

    Thanks so much…
    PS.: still struggling to get /me…

  35. Carol X June 16, 2010 at 10:12 am #

    Hi
    It’s not exactly related to your tutorial, but hopefully you can help me.

    I have an app in Flash, loaded via iFrame. I used the javascript SDK for the authorization, and managed to pass an access_token to flash via flashvars. From there, I fetch any graph object, such as ‘/me’ via URLRequest using this access_token I got. It works in Firefox but not in IE.

    Here’s a test application I set up when I tried to isolate the problem (no luck finding the cause for the 2032 error, though):
    http://apps.facebook.com/carolices

    You’d be such a hero if you could point me into any direction at all! ;D I’m stuck here.

    Could it be a problem in the access_token? Cookies? Anything else?

    Here’s my code for authorization (you can see the access token in the app if you want to paste directly into the browser’ address bar):

    ———————————————————–

    function generateFlash($obj){
            var currentTime = (new Date()).getTime();
            var flashvars = $obj;
    
            var params = {allowScriptAccess: "sameDomain"};
    
            var attributes = {
                id: "swfContent",
                name: "swfContent"
            };
            swfobject.embedSWF("?"+currentTime, "flashContent", "760", "630", "9.0.0",
            "swf/expressInstall.swf", flashvars, params, attributes);
        }
    
        function reloadPage(){
            window.top.location = "http://graph.facebook.com/oauth/authorize"
                + "?type=user_agent&client_id=" + ''
                + "&redirect_uri=" + ''
                + "&scope=user_location,offline_access"
                + "&display=page"
        }
        window.fbAsyncInit = function() {
            FB.init({	appId: '', 
                status: true, 
                cookie: true, 
                xfbml: true,
                channelUrl: '/channel.html'});
            FB.getLoginStatus(function(response) {
                if(response.status!="connected"){
                    reloadPage();
                }else{
                    if(response.session) {
                        generateFlash(response.session);
                    }else{
                        reloadPage();
                    }
                };
            })
        };
        (function() {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol +
                '//connect.facebook.net/en_US/all.js';
            document.getElementById('fb-root').appendChild(e);
        }());
    
    • Devon O. July 6, 2010 at 10:43 pm #

      Hello Carol (or anyone else reading this).

      Don’t suppose you or anyone else found a solution to this problem? I am facing the exact same situation. Just spent 3 days on a commercial app only to discover it will work in every browser but IE because of this 2032 error when retrieving data via the graph api. May need to build the thing over without using the new api. Nobody’s happy about that…

      d.

  36. Ian June 17, 2010 at 1:05 am #

    I was just testing out the invite code and noticed that the friends list, javascript pop-up and “additional invites via email” were all bigger than the container thus adding internal scrollbars to the page. I thought reducing the size in the invite.php page would do it, but it didn’t seem to work.

    Thanks for any advice. Your code has been very helpful.

  37. Dave June 17, 2010 at 9:35 pm #

    This is a silly question perhaps, but I haven’t been able to get a working combination. In the project setup, there is a base url and then an /iframe url being specified to Facebook.

    Do all of the code files go into /iframe?

  38. rutherford June 18, 2010 at 10:13 pm #

    Mahmud I have noticed that Facebook haven’t yet implemented the new graph API http request variables for the remove user callback – have you experienced this?

    Also in app settings on the migrate tab beneath ‘new permissions’ there is now another radio button set called ‘new SDK’. If I enable this I don’t get any request variables but if I leave it disabled I get the old ‘fb_sig_…’ ones as expected.

    I’d like another competent fb developer to investigate it. Let me know if you decide to give it a look.

    • mahmud ahsan June 19, 2010 at 12:37 am #

      It would be great if i can check asap, but currently i’m working in iphone/obj c so I couldn’t manage time. If you found the solution, then kindly comment the solution. thanks.

  39. Gary Danko June 20, 2010 at 1:09 am #

    My hosting provider has only PHP4.x available. Is there a way to make this work with PHP4.x? Or do I absolutely have to have PHP5 to make it work?

  40. Alfred June 20, 2010 at 10:00 am #

    Hi, thanks so much for sharing.

    I’m facing a weird problem I hope someone can help me out, this is the last bug before I deploy the app

    1. I login to facebook
    2. Access my app
    3. Session is null, so redirects to login url
    4. After login(auto), I’m redirected to my server URL instead of the canvas URL
    5. Subsequent access to the app has no probs, unless I logout and login again

    thanks! :)

  41. Syed June 20, 2010 at 1:02 pm #

    Hi,thanks for sharing this great post!

    can you tell me whats the prob for my below fbml code?

    i am having prob with Multi Friend Selector!

    i added this to my page

    See the below Code

    <fb:request-form
    action=""
    Method="POST"
    invite="true"
    type="sample network"
    content="YOUR MESSAGE GOES HERE”
    >

    If i use the above code it says Invalid Request and gives me an error!

    So later i tried many methods,then when i removed Method=”POST” it worked! i mean the invitations were sent successfully,but the prob is when i send the invitation using this method,i won’t see any message that it has been sent! and also it redirects me to my page wall,i tried with action=”” i added my fbml tab link,but when i did this it then redirected me to my fb home page,so can you tell me whats wrong?? or is it the same prob for all? i heard fb is improving? so due to that this thing is not working!!

    i know some fbml stuff but not expert!

    Please Let me know asap..

    thanks again:)

  42. alon June 20, 2010 at 8:13 pm #

    Hey,
    Im wondering, what code goes in the /iframe and what goes for the facebook connect url? when i try implementing the code it goes into a redirect loop of going to facebook and back to the app over and over.

  43. Ghido June 20, 2010 at 9:09 pm #

    Hi! This code works great with SDK 2.0.3, but it doesn’t work with 2.0.4 or 2.0.5. What is the problem?

    Another question: how can I make Facebook Dialog in an IFRAME app? For FBML I use Dialog object…

    • mahmud ahsan June 21, 2010 at 1:23 pm #

      Recently I am working in objective C/iphone, so I really couldn’t notice what changes facebook introduced. Sometimes I think application development for facebook sucks for facebook’s quick change. Whatever, if i know i’ll surely inform others and if you know then share with us. All fbml tags will not work in iframe. Rather use customize component like jquery features.

      • Ghido June 21, 2010 at 10:41 pm #

        I found a Javascript object to create Dialogs. You can find the code here ;)

  44. Ian June 21, 2010 at 7:14 am #

    Here’s an interesting issue. Just sent a friend request from my account to a test account. Signed out of my account.

    When I signed in on the test account and had it accept the request, the results of print_r($fbme); on the application should the UID for MY uid, not the test account’s info.

    Any ideas?

  45. Emmanuel June 21, 2010 at 1:29 pm #

    I tried both your test demo and mine’
    They keep on redirecting between 2 urls, after i had allow the application, and never went beyond
    This has been on for days
    I thought its a face book issue
    Or what do you think is wrong?
    Men, you have done an award-able job.
    Welldone

  46. alon June 21, 2010 at 2:05 pm #

    i found some weird issue i resolved. if anyone here is getting the redirection loop i had that. for some reason the getLoginUrl() returns canvas=0&connect=1 when the javascript takes over the parent window in my code.

    i tried implementing the code ontop of a framework called symfony, for some reason the $session var never got set and it never recieved a proper session after the allow screen loop. because of that it continued to redirect back and forth between the app and my dev server because the request allow screen was initilized with canvas=0.

    what i did to resolve it was avoid using the getLoginUrl() and building the login url myself, its just a couple of vars to pass and i set the canvas=1&connect=0 manually.

    once i did that it got the authorization loop working properly and not as a regular connect oauth login process. when you start the process with canvas=0&connect=1 it sends you back with an oauth_token and not session that your initially waiting for it. it works on first try but second it fails because you already have a session.

    building the url manually fixed the issue for me and its working fine. for some bizzare reason when you take over the parent iframe window it changes the url, i just placed a die() and printed the $loginUrl and then set it manually to the javascript.

    i wish there was an exp’ for the /connect and the /iframe url. but they are exactly the same for me. both go thru the fbmain.php code and load MVC style template with the template.php and home.php together.

    thats it :) hope i helped. i break my head on this issue for 2 days.

    • Emmanuel June 21, 2010 at 2:34 pm #

      pls can you provide me some sample code?

  47. alon June 21, 2010 at 3:36 pm #

    There isnt much sample code, just go to fbmain.php, it has two situations where it directs the parent iframe using javascript. where it says ‘$loginUrl’ put # at the start of the line and afterwards echo $loginUrl; die(); it will print the url you need, put that url instead of the $loginUrl in the javascript statement and remove the #.

    it will redirect you to the allow page and send you back properly.

    please note it only happens to me when i tried using it under an MVC php framework. running the code above works out of the box.

    all the redirection loop occures because of the canvas=0 and the connect=1.

  48. DanielJ June 21, 2010 at 9:36 pm #

    Hi Mahmud- This is a great start for IFrame work. I am having a problem with FB redirecting when I log in.

    The line causing the issue is:

    echo “top.location.href = ‘$loginUrl’;”;

    With $loginUrl I think causing the problem, I’ve tried Alon’s approach but this did not work.

    Does anyone have a work around on this?

  49. dhanasekar June 23, 2010 at 5:30 pm #

    hi all,
    i am new to facebook after downloading this code and insert it in facebook with the help of iframe and when i executr it the url is redircting to my local url like this
    http://127.0.0.1/iframeapp/index.php/?auth_token=82d70e137b30e67dab113d3fd705d34d

    i dont know whats happening..i think there is some pbm with session can any one help me.

    • mahmud ahsan June 23, 2010 at 6:02 pm #

      Please don’t use localhost, rather buy a host and upload your files there and test. Hope it will solve your problem

  50. snail June 24, 2010 at 2:22 pm #

    Hi, i get a lot from this article. But i met another problem in my app which based on iframe. I insert a text type input to the request-form,

    but, when i clicked the input box, the function of enterMsg(this) wasn’t called. Then i found that alert(document.getElementById(“msg”)); will return “null”. Buf if i put the out of the the js function will be called correctly. But i do want to submit the value of the text, so i have to place the text input inside the request-form. Oh i really don’t know how to resolove it, can you help me ? Thank you very much

    • mahmud ahsan June 24, 2010 at 3:56 pm #

      request-form is facebook component you couldn’t do much customize over it. The thing you can do, you can pass extra parameter by the action url. for example http://yoursite.com/yourapp?name=snail (this could be the request form’s action url).

      • snail June 24, 2010 at 5:14 pm #

        Thank you for your reply. In fact, add a of type text is valid, and i can get the value of it after select some friends and send my request. At last the text in the will be sent to my friends’s wall. But now i want implement such a effect: when i clicked the text area of the input, i wish a js function called. (for example onClick=”enterMsg(this)”). But it’s invalid. Can you give me some suggestion?

  51. Anzorf June 25, 2010 at 11:26 am #

    Thank a lot, but not added the monthly active users in the profile? .. how I can see them? Thanks is awesome

    • Anzorf June 26, 2010 at 3:55 am #

      Monthly Active Users no show me? somebody help?

  52. snail June 25, 2010 at 12:35 pm #

    My app is based on iFrame, when i add a “input of type text”, into the request-form, the value of the user inputted can be got after submited. This is all the same with that based on FBML. But the difference is that when i add a onClick event for the input, the function can be called if app is based on FBML, but can’t if it is based on iFrame. Can i have a event process function if my app is based on iFrame?

  53. Umair June 25, 2010 at 1:33 pm #

    Hi. First of all thanks for the excellent tutorial. A couple of days ago I uploaded the scripts on my server and was facing login redirection problem. I realized there was a problem with curl. This was the same problem faced by marcos cabrera and many others. To over come this, I added the following two lines in makeRequest function (facebook.php):

    $opts[CURLOPT_SSL_VERIFYHOST] = 0;
    $opts[CURLOPT_SSL_VERIFYPEER] = 0;
    

    So the function now looks like:

    protected function makeRequest($url, $params, $ch=null) {
        if (!$ch) {
          $ch = curl_init();
        }
    
        $opts = self::$CURL_OPTS;
        $opts[CURLOPT_POSTFIELDS] = $params;
        $opts[CURLOPT_URL] = $url;
        $opts[CURLOPT_SSL_VERIFYHOST] = 0;
        $opts[CURLOPT_SSL_VERIFYPEER] = 0;
        curl_setopt_array($ch, $opts);
        $result = curl_exec($ch);
        if ($result === false) {
          $e = new FacebookApiException(array(
            'error_code' => curl_errno($ch),
            'error'      => array(
              'message' => curl_error($ch),
              'type'    => 'CurlException',
            ),
          ));
          curl_close($ch);
          throw $e;
        }
        curl_close($ch);
        return $result;
      }
    

    This might not be the best solution but it works:-)

    • mahmud ahsan June 25, 2010 at 4:45 pm #

      Thank You Umair i hope it will help others who face the problem of redirection.

    • ilker July 5, 2010 at 6:48 pm #

      Did you try it with the new sdk ? (in migration tab options.)
      Thanks.

  54. Ann June 28, 2010 at 2:16 am #

    When I try to send an invite with the thinkdifferent app I get the following error

    403 Permission Denied
    You do not have permission for this request /demo/newfbconnect1/iframe/index.php?page=invite.php

    This is at url http://thinkdiff.net/demo/newfbconnect1/iframe/index.php?page=invite.php for http://apps.facebook.com/thinkdiffdemo/index.php?page=invite.php

  55. Nyong Grandong June 28, 2010 at 6:54 am #

    can you help me im getting eror in my app
    my app continuously redirect forever, this my apps please help me http://www.facebook.com/apps/application.php?id=130739116949774

  56. peter de clercq June 29, 2010 at 5:31 pm #

    everything seems to work for me but i get redirected outside facebook

    any idea what might have gone wrong?

    thank you btw it seems to be the best example i found online

    • Jason October 3, 2010 at 3:09 am #

      I am getting the same problem that Peter mentioned a while back. After first authorizing the application, it redirects me to my server and takes me out of facebook.

      It only does this the first time after authorization. Does anybody know what causes this?

  57. Juan June 29, 2010 at 10:00 pm #

    Good work!! Best documentation on the new facebook graph API.

    Very helpful, you should write a book, its in dire need for new developers to the facebook platform!!

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

      Writing book is a hard task, and very boring for facebook. Because facebook changes frequently. If I get any offer from any publisher I’ll consider :). Thanks for your advice.

  58. David June 30, 2010 at 11:52 pm #

    There seems to be an error in the Download link / package. I can’t download it complete. Can you please check this?

    Thank you!

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

      Download code link is working. I just checked and confirmed.

      • David July 1, 2010 at 3:38 am #

        Worked for me in Opera as well – just FF3 under Ubuntu 10 doesnt work – don’t know why.

        Thanks and have a great day – you made my day with your example codes ;-)

  59. Mick July 5, 2010 at 2:39 am #

    Thanks for the nice tutorial. I am only interested in invite.php and I would like to use it on our website (not as a facebook app inside an iframe). We are using the php-sdk and we have a valid facebook object initialized and we can retrieve user data, post updates etc using it and now we are trying to use your invite.php with it but it’s not working.

    We copied your invite.php class and replaced the variables but its just showing a blank page.It would help if you could provide some clues as to how to make it work on a webpage outside facebook.

    Thanks
    Mick

    • mahmud ahsan July 5, 2010 at 9:26 am #

      Did you correctly include and init the facebook javascript library for parsing the xfbml code of invite?

  60. Peyote July 5, 2010 at 3:56 pm #

    Hi Mahmud,

    I have used your sample as a base for an app I am writing. Great tutorial by the way :)

    I have got everything working as the tutorial as I simply uploaded that, changed my url’s etc to see it working fully before adding my own code.

    I have simply added my code inside a division and all that works well, the app works as required.

    I do have one issue though, its with the invite section.

    From within the app I can send an invite to a friend, that all seems to work fine, it informs me the invite has sent.

    The friend receives the invite, properly formatted etc, they click “accept” and get correctly redirected to the app after allowing permissions etc.

    The problem is that the friend will not see the app in his applications section of facebook, the only way they can access the app a second/third etc time is to put the app url into the browser.

    Have you seen this before?

    Thanks for the great tutorial :)

    • mahmud ahsan July 5, 2010 at 4:41 pm #

      You can add code of bookmark. fb:bookmark was used before to prompt user for bookmarking the application.

  61. Ghido July 5, 2010 at 9:09 pm #

    Hi! I released a PHP Class, using your tips!
    Please, check it and tell me what do you think: http://www.bigthink.it/classe-php-applicazioni-facebook-graph-api/

    The post is in Italian, but Class comments are in English.

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

      Good job. I hope it will help others to quickly use for their applications. You should also submit this class in phpclasses.org so that other users also can take advantage by using your class.

      cheers!

  62. nish July 6, 2010 at 4:32 pm #

    hi, when i tryed this i get error:

    HTTP Error 403.14 – Forbidden: Directory listing denied.

    I am stuck help me plz…

  63. tiffany July 7, 2010 at 2:55 am #

    Hi mahmud…It is really fantastic article. If you help me regarding my issue, I will be thank ful to you.

    I developed an facebook application.

    I used graph API and IFrame. When the user accept my application, I save user id in a text file.

    So, when the user remove my application, I need to deletet user id from my text file. For that, I gave my page link in the Post-authorize Callback URL in the authentication tab of the facebook application. So when user remove the app, it has to redirect to that link and needs to remove the corresponsidng user id from the text file.

    But the problem is, my app is not redirecting the user to the page I have specified in Post Authorize callback url.

    Please help me regarding this.

    thanks alot…

    • mahmud ahsan July 7, 2010 at 10:10 am #

      You have to use Post-Remove Callback URL in the application setting to remove user’s information from your database. Facebook pings this URL when a user removes your application. And it cannot be a Facebook-framed page.

      • tiffany July 8, 2010 at 3:36 am #

        Hello Mahmud ashan…I am very happy to get reply from you….

        So, coming to my problem,

        I used Post-Remove Callback URL. Here the problem is, when I remove the application, face book calls that URL three times. It is strange. what might be the reason.

        I go to Account –> Application settings –> and removing the application.

        Thank you for your time.

        • tiffany July 8, 2010 at 11:39 pm #

          Hi mahmud ashan…

          I developed my callback url in such a way that, it will count the number times it is called by face book server. Generally it is called 3 times, so at the 3rd time calling my page will do the required task.

          I did not find any other way.

          Probably this(calling the Post Authorize Callback URL 3 times by face book server) might be one of the major bug in face book.

          thanks,
          Tiffany.

          • mahmud ahsan July 10, 2010 at 1:53 pm #

            Yeah, this might be FB bug.

  64. tiffany July 9, 2010 at 5:50 am #

    Hi Mahmud Ahsan…

    I developed a face book application.

    If I run a php script to post on user’s wall, it should show the app name beside the post, but it is showing username beside the post.

    I use the following code to post on users wall:

    $attachment = array(
    ‘access_token’ => $this->access_token,
    ‘message’ => $this->message,
    ‘name’ => $this->name,
    ‘link’ => $this->link1,
    ‘description’ => $this->description,
    ‘picture’=>$this->picture,
    );

    $facebook->api(‘/’.$uid.’/feed’, ‘POST’, $attachment);

    So, to feed user’s wall, I put the above code in a separate php file and run the php file. It will get the user information by reading a csv file consists of uid, access token etc.

    Any Idea please to show the post is posted by app instead of user. How can I change above code to show the app name.

    Thanks alot.

    • mahmud ahsan July 10, 2010 at 2:07 pm #

      link (action link) parameter should be provided as json encoded value. for example here i provided the sample code of publishing stream using legacy api:

      try {
                          $actions                =   json_encode(array(array('text'=>'My Site', 'href'=>'http://thinkdiff.net')));
      
                          $param  =   array(
                                  'method'        =>  'stream.publish',
                                  'callback'      =>  '',
                                  'message'       =>  "my message",
                                  'attachment'    =>  '',
                                  'action_links'  =>  $actions,
                                  'target_id'     =>  '',
                                  'uid'           =>  '',
                                  'privacy'       =>  ''
                          );
                          $result   =   $facebook->api($param);
                      }
                      catch(Exception $o) {
                      }
      
      • Tiffany July 13, 2010 at 6:08 am #

        Hello Mahmud Ashan…

        Thanks a lot for the reply.

        I executed your code
        ———————————

        try {
        02
        $actions = json_encode(array(array(‘text’=>’My Site’, ‘href’=>’http://thinkdiff.net’)));
        03

        04
        $param = array(
        05
        ‘method’ => ‘stream.publish’,
        06
        ‘callback’ => ”,
        07
        ‘message’ => “my message”,
        08
        ‘attachment’ => ”,
        09
        ‘action_links’ => $actions,
        10
        ‘target_id’ => ”,
        11
        ‘uid’ => ”,
        12
        ‘privacy’ => ”
        13
        );
        14
        $result = $facebook->api($param);
        15
        }
        16
        catch(Exception $o) {
        17
        }
        ——————————————

        still it is showing the username beside the message. App name should be shown. But there should not be user name.

        Thank you very much.

  65. joe July 10, 2010 at 5:45 am #

    dude for real i want to hug you this has fixed so many of my problems that were caused by facebook documentation not explaining anything ever.

  66. Vishal July 11, 2010 at 8:57 pm #

    Hi Mahmud Ahsan,

    Thanks for the great tutorial.

    Its indeed the most updated tutorial on facebook development.

    But I am still unfortunate to make the things work.
    I have tried your code by just modifying the appId, key secret, base and canvas urls accordingly. But, after clicking on Allow access, it simply oscillates between two urls and I dont get the index page which should ideally come after authorization.

    Please help, its been over 3 days now.. :(

    Please suggest if I have to do anything special in connect and migration tabs…

    Thanks,
    Vishal

    • Bharathi July 11, 2010 at 9:12 pm #

      tell me the URL of your application.because i have experienced the same situation.so i ll help u if possible

      • Vishal July 11, 2010 at 10:19 pm #

        Hi Bharathi,

        Thanks for replying.

        The url for my application is: http://apps.facebook.com/std-lite/

        The code is exactly same as provided by Mahmud.

        My application url is: http://apps.facebook.com/std-lite/

        I am hosting it on http://vishals.0fees.net/iframe/

        Hope to see something positive :)

        Thanks,
        Vishal

        • Vishal July 13, 2010 at 1:56 pm #

          Feeling great to post comment on my own problem.

          Aneways, I’ve fixed the issue of infinite redirection.

          In my case, my session object was not being created and hence the infinite redirection was happening even though I was getting session in the request object i.e $_REQUEST['session'] after clicking on allow access.
          So, the problem was that in getsession function in facebook.php, the jsondecode was not returning the session from $_REQUEST['session'] because the $_REQUEST['session'] was html hex encoded, so I just decoded the $_REQUEST['session'] using urldecode and then passed it to json_decode and everything works fine now… :). I don’t know if its a good fix or not but at least I can see a better screen now.

          Thanks,
          vishal

          • venkat July 21, 2010 at 2:41 am #

            Vishal,

            Could you please put/send the code how you decoded what you made chage viceversa. I am getting the same issue.

            Thanks,
            Venkat

  67. Joe July 12, 2010 at 11:31 am #

    i have a quick question is it possible to send notifications to the apps users friends with the graph api?

    • mahmud ahsan July 13, 2010 at 11:53 pm #

      Facebook closed notification system for applications. So you can only send email instead of notifications.

      • Joe July 14, 2010 at 11:01 pm #

        by email do you mean facebook inbox or thier actual email and could you point me in the right direction to do that? also thanks for responding. because no one on the facebook dev forums ever does

        • mahmud ahsan July 15, 2010 at 1:37 pm #

          by email means, user’s original email. if user approves your application and email extended permission you’re able to retrieve user’s email.

  68. Jonas July 15, 2010 at 10:07 pm #

    hey i have a question about extended permissions..

    if i declare:

    ‘req_perms’ => ‘email,publish_stream,status_update,user_birthday,user_location,user_work_history’

    it drops me a single auth page for every rule.. y are they not shown up on one single req. site like its normal.. ?

    • mahmud ahsan July 16, 2010 at 1:34 am #

      I don’t know, this is facebook new style :)

      • Jonas July 16, 2010 at 3:03 am #

        but its the same code like yours and on your demo it looks different.. hum

  69. Gianluca July 16, 2010 at 9:25 pm #

    Hi there,
    is it correct to have all that info in the url query string?(such as the access token)
    shouldn’t it be secret?
    how can i authenticate and be redirected to the app with a clean url ( http://apps.facebook.com/XXMYAPPXX/ ) ?
    Thanks!

  70. Shanavas c July 17, 2010 at 9:41 pm #

    Hi
    I tried to workout thecode u have given, but i am always getting an curl exeptin. Can u tel me y it is hapenig so. I checked, the curl is enabled in myserver. I am usng php 5.2.
    Hope i will get some replay soon.
    With regards
    Shanavas C

  71. Rico Chen July 21, 2010 at 2:25 am #

    Hello,
    I have the same problem as Shanavas C. I also have php 5.2.13 with curl enabled. I also tried the solution from Umair but still I keep getting timeout error (page will load but the iframe will show the debug information after nearly 1 minute). Can someone shed some light on this? Thanks.

    • mahmud ahsan July 21, 2010 at 6:21 pm #

      I also don’t know why this curl exception/error shown. In my hosting its not showing. I also tried in facebook forum but didn’t find any good solution for it.

  72. Roger July 24, 2010 at 5:29 pm #

    I was so happy to find this code as I’ve been beating my head against a brick wall for days. However, I’ve set everything up as per instructions, when I run the application it just keeps defaulting to the base domain. I checked out the value of the $loginUrl and it doesn’t contain the full path to the folder with the script files in it. I am running these files on a window server, but it has php 5 installed on it. I’ve set up the canvas and connect urls properly… please can someone out there help me?

    • Roger July 24, 2010 at 6:18 pm #

      Ive now worked out that the problem is rooted in the following bit of script

      catch (FacebookApiException $e) {

      echo “top.location.href = ‘$loginUrl’;”;
      exit;
      }

      the question I have is – why is the exception being thrown?

      • Roger July 24, 2010 at 6:34 pm #

        Well, I have solved it all by myself – horray!

        If anyone out there is bored enough to read my solution here it is:

        I used echo $e to discover that the exception being thrown was a curl exception – 60 I think – to do with SSL certification. Probably being thrown because I’m running php on a windows server or something. Anyway, I added these 2 lines of code

        $opts[CURLOPT_SSL_VERIFYPEER] = false;
        $opts[CURLOPT_CAINFO] = ‘ca-bundle.crt’;

        to the make request method in the facebook.php file. Right underneath

        $opts = self::$CURL_OPTS;

        The app then worked but was still producing an error – which tracked down to this line of code in the facebook.php file

        $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        On line 730

        I changed the REQUEST_URI to PHP_SELF

        $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

        And lo and behold! It Worked!!!

        Hope this helps someone out there

        • Roger July 24, 2010 at 6:44 pm #

          For the sake of completion – you need to add the ca-bundle.crt file to your application directory

          I found this at

          http://www.tehuber.com/phps/cabundlegen.phps

        • dave July 26, 2010 at 7:28 am #

          Thanks very much Roger, doing both of these things also stopped the looping and base domain problem for me. I did have to wait a few minutes (as always) for the Facebook app changes.

        • Dondie July 28, 2010 at 5:20 pm #

          ive done what youve teach on the infinite loop but still it is looping… please help me…

          thanks…

          http://apps.facebook.com/mightyfoobar

        • maro6th December 9, 2010 at 1:12 am #

          Thanks a lot!
          it works!

        • Federico Noto January 5, 2011 at 2:00 pm #

          Thanks so much!!!!

  73. kimou July 24, 2010 at 5:59 pm #

    what is the diference between canvas callback url and connect url.
    for example i have the project in testhtmlkimou.hebergratuit.com/iframeapp/
    =>the connect url is testhtmlkimou.hebergratuit.com/ ???
    or an other url

    • kimou July 24, 2010 at 6:27 pm #

      hi mahmud ahsan
      it was not worked !!!!!!
      I have an infinite loop.
      please check:http://testhtmlkimou.hebergratuit.com/iframeapp/
      apps.facebook.com/bornonwhatday/
      thank you in advance

      • kimou July 24, 2010 at 8:02 pm #

        I think the problem is here
        fbmain.php

        catch (FacebookApiException $e) {
        echo “top.location.href = ‘$loginUrl’;”;

        exit;
        }

        • kimou July 24, 2010 at 8:04 pm #

          echo “top.location.href = ‘$loginUrl’;”;

        • Roger July 24, 2010 at 8:04 pm #

          Have you seen my post above – I had the same issue with it infinitely looping around…

          • kimou July 24, 2010 at 8:33 pm #

            :(the problem remains

  74. kimou July 24, 2010 at 8:36 pm #

    echo $e;——–>CurlException: 6: Couldn’t resolve host ‘graph.facebook.com’

  75. Mick July 25, 2010 at 1:08 pm #

    Hi,
    Is there anyway to make the fb:multi-friend-selector work just with the access token?

    Right now it works fine if the user is logged into facebook but once the user logs out, it does not works even though i have a valid access token for the user with offline-access permission.

    Any help would be appreciated

    Thanks

  76. Hirklins July 26, 2010 at 3:09 pm #

    Hi,
    Thanks for the great tutorial.. One of the best around for me. I have a question on friend request. I notice that from your piece of code, we have to click on the friend request to and it will call reques.php.

    I edit your code and manage to add the friend request on the DIV tab. How can i do once the user submit the request.. it will bring back to the tap.

    <fb:request-form
    action="/index.php?page=home.php”
    target=”_top”
    method=”POST”
    invite=”true”
    type=”Football Fight Club”
    content=”Try This new football Fight Club. Lead your club to the top! <fb:req-choice url='’ label=’Accept’ />”
    >

    thanks!

    • mahmud ahsan July 27, 2010 at 12:51 am #

      just fill the action=”” parameter with your page location.

  77. Robin July 27, 2010 at 11:48 pm #

    Hello Ahsan , there a question.

    Must the rendered method under cavas setting be Iframe? I set to FBML and it was blank.

    Another thing is, facebook apps took forever to load a simple comment box!

    I could get my comment box working though by directly accessing the php page from my www root.

  78. Matt Rouse July 28, 2010 at 4:15 am #

    Some quick solutions to some issues I saw spread in the comments:
    1. when you unzip the files, the dir is called iframeapp not iframe as shown in the URLs in the example. Name them the same.
    2. URLs in code need to have / included on the end.
    3. I made my connect URL the same as my canvas url.

    • Dondie July 28, 2010 at 5:00 pm #

      hi matt i use your recomendation but it didnt work too…
      i download the whole file and update everey thing but the output is just like this…

      http://apps.facebook.com/mightyfoobar/

      please help

      • Matt Rouse July 28, 2010 at 11:19 pm #

        I would say you probably have the URL incorrect for canvas or connect page. Check those settings again and make sure they match the directory name on your server and what you put into the fbmain. Also, check your app ID, secret and api key.

        • Dondie July 30, 2010 at 7:54 am #

          ive check them all and it seem that all the data are correct…

  79. akaayy July 28, 2010 at 9:46 am #

    Is this tutorial applies to FBML method??

  80. akaayy July 28, 2010 at 9:50 am #

    Is this tutorial applies to FBML method?? if not, where I can find the tutorial for FBML method, I hope you one like this article, plz tell me where i can get it ^^
    thank you very mach~

  81. Dondie July 28, 2010 at 10:36 am #

    code not working please help me my facebook app is refreshing and refreshing…

    • Felipe Roberto July 29, 2010 at 1:12 am #

      It’s happening with me, too!

  82. Dondie July 28, 2010 at 11:11 am #

    not working please help

  83. akaayy July 28, 2010 at 11:16 am #

    I download and run your code on my server, it show some error:

    FacebookApiException Object
    (
    [result:protected] => Array
    (
    [error_code] => 6
    [error] => Array
    (
    [message] => name lookup timed out
    [type] => CurlException
    )

    )

    [message:protected] => name lookup timed out
    [string:private] =>
    => 6
    [file:protected] => /var/www/html/facebook.php
    [line:protected] => 511
    [trace:private] => Array

    …..
    ……
    …….

    how can I solve this problem?

  84. Vishal July 28, 2010 at 1:51 pm #

    Hi Mahmud,

    The demo http://apps.facebook.com/thinkdiffdemo/ seems to work fine other than the invite feature.

    There are following issues:
    ## If you press skip and do not select any friends in the selection box, It loads another page in the iframe saying “The page you requested was not found.”

    ## No friends coming in the box though it might be temporary facebook issue.

    ## The alignment of the confirmation popup after you click on send is not proper.

    Could you please help to figure out how to fix that??

    Thanks for your help.

    -Vishal

  85. Dondie July 28, 2010 at 2:41 pm #

    Please anyone help me i download the whole source code and edit the api, apiid, and secret but it seems the apps not working properly

    http://apps.facebook.com/mightyfoobar/

    please thanks

  86. Dondie July 28, 2010 at 2:41 pm #

    please help me

  87. Birkoff August 2, 2010 at 12:59 pm #

    Hi Dondie,
    I see your fb app is working now, mine keeps refreshing, what should i do?

  88. havanakoda August 2, 2010 at 5:01 pm #

    Hi Mahmud, thanks a lot for yout tutorial, it’s a very useful work. I have a question:
    in my facebook canvas application I pass data by form using the method you described above; I’m monitoring the situation but somethimes, very seldom, the variable $_REQUEST['submit'] is not setted. Could you tell me why ?

  89. Peyote August 4, 2010 at 4:58 pm #

    Hi Mahmud,

    I am still tinkering with FB stuff and have used this tutorial as a basis to try ideas etc

    Do you know if you can set the wall publish to be automatic? I have tried setting auto_publish: true in the FB.ui stream.publish param list but it will simply bring up the dialog to publish.

    cheers,
    P

    • mahmud ahsan August 5, 2010 at 1:11 am #

      Autopublish is different, if user approve publish_stream and offline permission, using session key, you can auto publish to user’s wall.

      • Jangla October 1, 2010 at 4:52 pm #

        Oddly, the application I’m developing has got both those permissions and yet I still get the dialog.

  90. Vishal August 6, 2010 at 8:50 pm #

    Hi guys,

    Can someone help me with the popup cutoff issue in invite friends feature of the iframe application we are discussing here.

    Please help guys.

    Thanks,
    Vishal

    • Matt Rouse August 6, 2010 at 10:16 pm #

      I have run into a similar issue with a flash application that posts to someone’s wall. The facebook popup loads behind the flash object and cannot be seen. Anyone else had this issue?

  91. buzzknow August 6, 2010 at 11:12 pm #

    really nice mahmud :)

    i learn a lot from u :)

  92. Kiko August 7, 2010 at 4:43 am #

    hello,
    i have uploaded your script and it works perfectly.
    my problem now is i want to post to my friends wall not feed/homepage and i cant convert your stream publish code to work like this. permission is ok, but can still post to my friends wall.
    do you have a complete and sample code for this, i am using iframe?
    ive been trying to solve this one for 2 weeks now.
    pls help me.
    thank you very much.

    • mahmud ahsan August 7, 2010 at 9:41 am #

      Its very easy, you have to just pass your friend’s facebook uid as a parameter in the code. please check the facebook documentation for it.

  93. Dipen August 8, 2010 at 5:43 pm #

    This is just awesome. Very awesome article. Now i will start with editing your code and making an app. I will get back to you if i have problem. Thanks a lot mate. Thanks a ton.

  94. kipdrordy August 16, 2010 at 4:36 am #

    hi guys, how did u solve the redirection loop problem? is there a solution to this or still nothing?

  95. M.M.H.Masud August 16, 2010 at 9:57 am #

    Hello

    I just read your post and found it really great. the way you explain the app is really good for any dev. I have found everything working and understand the functionality.

    But i don’t know, why the invite.php is not working. i tried couple of example also, but sometime its shows error or sometime its shows blank page.

    Currently i am developing a iframe base application and i need the invite feature badly. So can you please help me regarding this invite feature with graph API. You can also send me some workable link for this app.

    thanks

  96. M.M.H.Masud August 16, 2010 at 3:39 pm #

    thanks mahmud, i just got it working. anyway thanks for this early response. :)

  97. kipdrordy August 18, 2010 at 2:39 pm #

    the application keeps refreshing and refreshing after the permissions screen, how can i solve the problem? HElp!

    • Dave Shaw August 20, 2010 at 4:50 am #

      @kipdrordy
      I have the same problem. Just ran the sample today and it loops infinitely.

  98. manish August 20, 2010 at 12:36 pm #

    nice

  99. joshul August 20, 2010 at 7:40 pm #

    This example is not for graph api.

  100. Edwin August 23, 2010 at 4:08 pm #

    ahsan, you rocks!

    I successfully get it working.

    thank you!

    I’m facing an issue with comment adding.

    do you know how to deal with this code?

    <div id="user">Name: <input size="27" name="name" /><br /><fb:login-button onlogin="update_user_box();"></fb:login-button></div>

    I’m using a video script and I expected that the name given by facebook is not loaded in the form??

  101. chiemeka August 24, 2010 at 4:07 am #

    I dont know why, but the code still wont run. I am new to PHP, I dont know if there is anything i have missed.
    error “Parse error: syntax error, unexpected ‘{‘ in \\boswinfs02\home\users\web\b2526\ez.chiemekailo\silversurfonline\topconverter\fb\index.php on line 7″

    • CLaudio September 20, 2010 at 12:04 pm #

      Excellent work !

      But if I hit INVITE on Your demo, then SKIP, follows a white page, demo is hanging.

      What can I do ?

      Thanks

  102. chiemeka August 24, 2010 at 4:15 am #

    I now renamed the index.php to index.php5, and I get this new error message:
    “Error
    An error occurred with TopConverter. Please try again later.

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: next is not owned by the application”

  103. Mark August 24, 2010 at 7:35 pm #

    I noticed a problem with this code, If you log on as one user, visit the app, log out of facebook and then log in as a different user (in the same browser) then it will be as if the first user was still logged in. It is because of the cookie. I can’t for the life of me work out how to write over the cookie when a new $_REQUEST session is sent.

    I have posted the same question on stackoverflow here: http://stackoverflow.com/questions/3555682/facebook-app-cookie-not-set-to-new-session-data-when-request-session-is-present

  104. konfus August 27, 2010 at 8:05 pm #

    5. Form Submission technique and getting Data

    Not woriking in IE, $_POST is empty.

    Google Chrome and FF are fine.

    • konfus August 27, 2010 at 9:19 pm #

      had an include of fbmain.php in my submission.php

      no it works :/

      • Jan November 3, 2010 at 9:49 am #

        I dont know if it is the right solution, but I inserted

        header(‘P3P:CP=”IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT”‘);

        whithin php tags

        At the top of the template.php file and now IE works.

        Jan

        • mahmud ahsan November 3, 2010 at 9:07 pm #

          Thanks for your information.

  105. Shani August 29, 2010 at 11:35 pm #

    Thank for this great tutorial.

    can I send privet messages to my app users and their friends?

    Thanks

  106. Deepesh August 31, 2010 at 4:02 am #

    Hi thanks for this great tutorial. This is the best I have found till now. However my app keeps redirecting forever after allowing permissions. Is there any workaround for this problem?

  107. Noirita August 31, 2010 at 8:23 pm #

    Thanks Mahmud for this wonderful article.
    @Deepesh , Try to clear your browser cookie cache and remove your application and add it again.

  108. Kyle MacDonald September 1, 2010 at 3:59 am #

    @Deepesh – There’s a very good chance your issue has to do with this issue and a CURL option with the SDK – http://forum.developers.facebook.net/viewtopic.php?id=58016

    try setting these values after you instantiate the Facebook class (fbmain.php line 24-28)

    Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
    Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;

    • Duane November 23, 2010 at 9:01 pm #

      Those 2 lines worked for me

  109. Dave S September 1, 2010 at 9:03 am #

    Followed all the advice in this list and made the settings correct and I still have an endless loop off this code:

    if (!$session) {
    echo “<script type=’text/javascript’>top.location.href = ‘$loginUrl’;</script>”;
    exit;
    }

    Any ideas… ?

  110. Dave S September 1, 2010 at 9:37 am #

    OK I just checked my application settings and found that facebook no longer has “facebook connect settings” section so I cannot set my Connect URL property. I do not know if this cause the infinite looping problem ! and some others have and I would appreciate the feedback from other members that have had success with these scripts to get some help here.

    • mahmud ahsan September 1, 2010 at 1:03 pm #

      No, you don’t need facebook connect setting. You can checkout http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/ this article to make the solution in alternative way.

      • Dave S September 7, 2010 at 5:50 am #

        Thanks mahmud. I am glad you got out from under the iphone app to help me. I will test your recommendation tomorrow and report back.

        • Dave S September 8, 2010 at 4:07 am #

          I copied all your code into my site, changed the settings and ran it. The html showed up first go and I clicked the login button and a window popped up with the familiar log form. After logging in the window stayed and reloaded the initial html from my first run through the script.

          Not a happy fellow here.

          • Jordan314 September 27, 2010 at 4:35 pm #

            I’m having the exact same problem. Either if(!session) puts me in an endless redirect loop, or the fb:login-button button opens a new window and goes from there in the new window.

          • Jordan314 October 7, 2010 at 1:42 pm #

            Ok my endless redirect problem was forgetting to upload template.php. :-$
            I also ran into a misconfiguration problem where if my canvas URL was incorrect, the app would actually get authorized without the users’ permission. It would keep appearing in my application settings even though I never clicked “Allow” in the app. I’m not sure how I did that but wonder if it’s a security flaw. o.O
            Finally, I realized that the baseUrl and AppBaseUrl should point to directories only, even if you’re pointing to a file other than index.php. If I tried pointing the baseUrl to test.php for instance it wouldn’t work, it just has to be the directory.

  111. kipdrordy September 1, 2010 at 1:59 pm #

    firstly i used the popup auth, that solved pretty much the problem, but i was not happy with that. so i switched to FBML and used the specific tag, which i like more than popup auth.
    you can check it out here: http://apps.facebook.com/polpopaolo/
    i think that infinite loop is caused by our webhost.
    can u suggest me a cheap webhost for facebook apps around 70-100 dollars for year?

    • mahmud ahsan September 1, 2010 at 4:20 pm #

      You can buy hosting from hostgator.com. Their service is awesome.

  112. HASNAIN September 1, 2010 at 7:00 pm #

    Hi
    can anyone tell me how to get extended permission with require_login($required_permissions = ‘publish_stream’);
    coz it only asks for basic info and not asks for extended permissions so what modifications i hav to made to get this code work.

  113. Diego September 4, 2010 at 5:33 am #

    Hi mahmud, thanks for the tutorial, great stuff!!

    I have a question regarding Safari and IE. I’ve read in some forums that you have to send a P3P header to allow cross-domain cookies.

    I haven’t seen anything like that on your code, but your demo app works perfectly in Safari… and mine doesn’t :(

    Are you sending those headers in your demo app?

    Thanks!

    • Fabio September 5, 2010 at 10:30 pm #

      I’ve the same problem about cross-cookies and Safari. Why your demo works perfectly in Safari?

      thanks!

    • mahmud ahsan September 6, 2010 at 8:26 pm #

      No, the code you can download is exactly same as the demo.

  114. Prashant September 6, 2010 at 6:10 pm #

    Hello All,
    Plzz tel me how to get the secret api key for facebook to build app’s on android

  115. Trevor Brooks September 10, 2010 at 10:30 am #

    Another victim of the infinite loop. None of the above mentioned fixes did it for me.

    • nishant December 14, 2010 at 1:54 pm #

      I am facing redirect problem only in IE 7. Anyone have any idea how to solve.

  116. Dave Pratt September 10, 2010 at 11:41 pm #

    Great article. These are the sort of tutorials that Facebook themselves should be providing…

  117. keeran September 12, 2010 at 2:53 pm #

    I am using your Stream Publish code but I am getting error

    Application response error

    The post’s links must direct to the application’s connect or canvas URL. You can see this because you are one of the developers of the app.

    • mahmud ahsan September 12, 2010 at 11:20 pm #

      Try to give application url as link not other url.

      • keeran September 12, 2010 at 11:59 pm #

        Really nice article thanks Mahmud Ahsan… its working fine..

        How to post a HTML content in face book wall. In my app I need to post some 5 friends images in wall but I don’t know how to post images.

      • keeran September 15, 2010 at 3:43 pm #

        Hi

        I am waiting for your reply could you please tell me how to post 5 friends images in wall

  118. kipdrordy September 12, 2010 at 2:58 pm #

    i suggest to all people with infinite loop problem to develope in FBML language, it is pretty easy even if documentation is poor. the problem with permission persists but with FBML we have another function to call it, that generates no loop. check it out how i implemented it in a button: http://apps.facebook.com/polpopaolo/
    the effect is like a javascript popup, very cool in my opinion. ( click on button “Lancia”)

  119. Dave S September 12, 2010 at 11:45 pm #

    @mahmud ahsan
    I found a way to stop the infinite looping from another site and I recommend altering the code from above in this section:
    $loginUrl = $facebook->getLoginUrl(
    array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘email,publish_stream,status_update,user_birthday, user_location,user_work_history’
    )
    );

    To Be this:
    $loginUrl = $facebook->getLoginUrl(
    array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘email,publish_stream,status_update,user_birthday, user_location,user_work_history’,
    ‘next’ => ‘http://apps.facebook.com/livesofdragons/play.php’,
    ‘cancel_url’ => ‘http://apps.facebook.com/livesofdragons/cancel/’
    )

    Where ‘next’ is the url of the script to handle your application after they have logged in and authorized. cancel_url is for when the user cancels the authorization process, I think as I have not tested it yet.

    I hope this helps.
    );

    • Dave S September 12, 2010 at 11:46 pm #

      Just change “livesofdragons” to your applications name.

  120. Fenil Desai September 13, 2010 at 1:08 pm #

    Hi Mahmud,

    Can u provide a similar example in .NET/C#?

  121. Tran Vuong Quoc Thieu September 14, 2010 at 8:04 am #

    I have a problem but i can’t solve. Can you solve???

    FacebookApiException Object
    (
    [result:protected] => Array
    (
    [error_code] => 6
    [error] => Array
    (
    [message] => Couldn’t resolve host ‘graph.facebook.com’
    [type] => CurlException
    )

    )

    [message:protected] => Couldn’t resolve host ‘graph.facebook.com’
    [string:private] =>
    => 6
    [file:protected] => /home/golamcha/public_html/demo/thieu/iframe/facebook.php
    [line:protected] => 513
    [trace:private] => Array

    • Dave S September 15, 2010 at 4:01 am #

      Tran.
      Regarding “Couldn’t resolve host ‘graph.facebook.com’”
      Maybe you forgot to use “https://graph.facebook.com”

  122. nico September 15, 2010 at 1:11 am #

    Hi All,

    I’m having the same problem that some of the guys in this discussion. My App. keeps refreshing and refreshing. Does anyone know how to fix it or what is going on?
    Thanks!

    Nico.

    • Dave S September 15, 2010 at 3:59 am #

      Nico check out my post from September 12, 2010 at 11:45 pm. That might help.

      • nico September 15, 2010 at 6:13 am #

        Hi Dave,
        Thanks for your reply, I changed this:

        //Facebook Authentication part
            $session = $facebook->getSession();
            $loginUrl = $facebook->getLoginUrl(
                    array(
                    'canvas'    => 1,
                    'fbconnect' => 0,
                    'req_perms' => 'email,publish_stream,status_update,user_birthday, user_location,user_work_history'
                    )
            );
        
            $fbme = null;
        
            if (!$session) {
                echo "top.location.href = '$loginUrl';";
                exit;
            }
            else {
                try {
                    $uid      =   $facebook->getUser();
                    $fbme     =   $facebook->api('/me');
        
                } catch (FacebookApiException $e) {
                    echo "top.location.href = '$loginUrl';";
                    exit;
                }
            }
        

        TO THIS:

        //Facebook Authentication part
            $session = $facebook->getSession();
            $loginUrl = $facebook->getLoginUrl(
                    array(
                    'canvas'    => 1,
                    'fbconnect' => 0,
                    'req_perms' => 'email,publish_stream,status_update,user_birthday, user_location,user_work_history'
                    )
            );
        
            $fbme = null;
        
            if (!$session) {
                echo "top.location.href = '$loginUrl';";
                exit;
            }
            else {
                try {
                    $uid      =   $facebook->getUser();
                    $fbme     =   $facebook->api('/me');
        
                } catch (FacebookApiException $e) {
        
                }
            }
        

        And it worked as a champ!

        Tomorrow I will give it a try to your code. Thanks again!

        Nico.

  123. Steven September 15, 2010 at 10:51 am #

    Can you post how to display all the user’s friend’s names and profile pictures when done in an iframe and using the graph api?

  124. The Minister September 16, 2010 at 5:17 pm #

    Thanks for the tutorial, which I found in desperation from the FB documentation. From zero to finished in a couple of days. I even kept your jquery tabs, cause they looked so well. See http://www.facebook.com/apps/application.php?id=265885216800

    • mahmud ahsan September 16, 2010 at 9:19 pm #

      Thank You, feeling good that it helps you.

  125. 谢彬 September 17, 2010 at 11:27 am #

    我来自中国,太感谢了,这样的文章太难找了—-great !good! perfect! it help me alot

  126. Valter Wierzba September 18, 2010 at 5:45 pm #

    If it weren’t for this guide, i would never have been able to make facebook apps. Thanks!

    Greetings from Sweden

  127. Joe September 21, 2010 at 1:13 am #

    thanks for the tutorial.

    Am I correct in saying that this is a standalone facebook application and one that can never be added to a tab on my page?

    thanks

    • mahmud ahsan September 21, 2010 at 2:56 am #

      Yes you’re right. This is a standalone application.

  128. Joe September 21, 2010 at 4:08 am #

    Mahmud,
    I’ve been struggling to make an app that reads rss feed as a tab on a facebook page (needs to read javascript). I have the app working as a stand alone (thanks to your tutorials). Do you have any insight to any good tutorials about how to do this?

    thanks again

  129. Matt Rouse September 21, 2010 at 4:34 am #

    This took me forever to figure out, but what you need to do is to go to the Fan Page for your app you created and then click on “Add this to my Page” and that gives you a list of other Fan Pages you created and then it will add it.

  130. Joe September 21, 2010 at 8:37 am #

    Hi Matt,
    By “Fan page”, do you mean “Like” button? Not having success yet but am hopeful.
    thanks

  131. Matt Rouse September 21, 2010 at 11:07 am #

    A Fan Page is a page created for a specific company or product. Look at this RSS blog tab I created: http://www.facebook.com/pages/Poolapolooza/142427862454621?v=app_154085114620986&ref=ts

    • Joe September 22, 2010 at 1:21 am #

      What tool did you use to parse out your rss feed? I used feed2j for what I’m working on.

  132. Joe September 21, 2010 at 10:29 pm #

    This is exactly what I’m trying to do! It appears fan pages don’t exist anymore though so am attempting to associtate a new page with my app and “Add it to my page” from there. So far, have not been successful.

  133. Rob September 25, 2010 at 12:36 am #

    I’m a bit of a newbie when it comes to javascript sorry pardon me if my issue is pretty basic. Stream Publish, Status Update, and Frame Size are not working for me. I get a javascript error: ‘FB’ is undefined

    Can anyone help?

    • Rob September 25, 2010 at 12:40 am #

      never mind…some kind of network firewall issue…

  134. Claudio September 27, 2010 at 9:47 am #

    Redirect after invite had been send: Your instructions say:
    ……

    $string = “top.location.href=’{$fbconfig['appBaseUrl']}’;”;
    echo “Use the following javascript code to redirect user “;
    echo htmlentities($string, ENT_QUOTES);

    …..

    I tried around hours now and I do not figure out how to make it right. How should the redirect finally look ?

    Thanks for any help ! I am still impressed of this excellent work !!!

    • Claudio September 27, 2010 at 10:41 am #

      Finally found what works, but I am not sure it is correct that way….however, for everybody to know….

      if (isset($_REQUEST['ids'])){
      print “”;
      print “top.location.href=’http://apps.facebook.com/MYAPP’;”;
      print “”;
      }
      else {

      ….

  135. Bibhash September 29, 2010 at 5:08 pm #

    Hi Mahmud,

    Its quite a good learning material. I appreciate it.
    I tried implementing the status updates from application by your javascript method. But it is not triggering the javascript.

    Am I doing something wrong ?
    I have made a separate js file in which the code for posting status updates exists. How do I include the script into the app ?

    • mahmud ahsan September 30, 2010 at 10:54 am #

      Please check that you successfully loaded the js-sdk before calling javascript api.

  136. harun October 2, 2010 at 4:38 am #

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

  137. Kobus Kemp October 4, 2010 at 6:44 pm #

    Hi All.
    I am looking for a PHP developer for a client based in Pretoria. If anybody is interested please send your CV to kobus@careerminded.co.za. Thanks, Kobus

  138. eniraka October 5, 2010 at 7:36 pm #

    Hello,

    I also have the refresh problem. I have tried all you said before, (curl opt or adding a “next” url) but it’s still happening. Did someone find anything else?

    Thank you

  139. eniraka October 5, 2010 at 7:37 pm #

    The tutorial is really good anyway. Thank you very much Mamhud.

  140. eniraka October 5, 2010 at 9:41 pm #

    Hello again,

    I have finally found the solution. I’ve tried on another server and it’s working perfectly. The problem war because de json extension wasn’t installed…
    Thank you again for the tutorial.

  141. Andreas October 5, 2010 at 9:53 pm #

    Thank you for your efforts. This tutorial is far more explanatory than the official FB documentation and very easy to follow. You have saved me a lot of time. Thanks a bunch!

  142. Xaris October 6, 2010 at 5:38 am #

    Hello,
    thanks to Mahmud for this excellent tutorial.
    I’m facing a problem where when a user is not logged in and if the URL is apps.facebook.com/myapp/ a 403 Access denied message is showing in the iframe.
    But when i put apps.facebook.com/myapp/index.php the redirect to the login page is working fine.
    Curl and Json are installed on the server.
    Any hints would be really appreciated…

    • mahmud ahsan October 6, 2010 at 10:09 am #

      use .htaccess to redirect index.php when myapp/ is browse.

  143. Xaris October 6, 2010 at 4:40 pm #

    Thanks for the quick response Mahmud.
    I’m not sure if this helps, because the Canvas URL http://mysite.com/fb/myproject/ is redirected just fine to the login URL.
    Only this Canvas Page URL (apps.facebook.com/myapp/) has the problem and shows 403 Access denied error.
    If i load the iframe with the error message in another tab the URL is
    http://mysite.com/fb/myproject/?fb_sig_in_iframe=1&fb_sig_locale=en_US&fb_sig_in_new_facebook=1

  144. Uuganbayar October 8, 2010 at 3:26 pm #

    Please provide me if you post new article… Article was excellent and thank you very very much… That is exactly what I was looking for… Good luck and thanks again

  145. AlexG October 8, 2010 at 3:53 pm #

    YOur application “Invite” feature doesnt work in Opera browser, but works fine in Firefox.
    Generally, Opera seem to work bad with FBML
    Do you have any ideas why Opera behaves like that?
    IE also has issues with <fb:request-form

    • mahmud ahsan October 8, 2010 at 11:12 pm #

      No I don’t know these issues regarding Opera browser. Do you please check in facebook documentation if they properly support for opera browser or not.

      • AlexG October 9, 2010 at 12:52 pm #

        Opera also doesnt manage properly cookies. Maybe its about iFrame content from different location.
        I am trying to solve this issue.
        You can check this by opening the “invite” page of Demo in Opera.
        If anyone knows how to solve it please write.
        Thanks

  146. suryakant October 12, 2010 at 5:34 pm #

    I have problem when my iframe size is increase but my bookmark buttion not working or not displaying any message

  147. Ardi October 13, 2010 at 9:10 pm #

    Dude, you’re totally awesome… thanks a lot, you really save my life here. Been looking all over the place for tutorial of fb apps, but so far none of them were as best as this one.

    Thanks and respect :-)

  148. Benyamin Ragil October 14, 2010 at 2:35 pm #

    Hello Mahmud, i would like to sat thanks for this great tutorial. I tried this tutorial but i have problem. I follow all the tutorial, when i go to my apps page in facebook (apps.facebook.com/myapp) it’s loading and reloading it’s self. nothing printed in the screen. what went wrong ? please give me light here… thanks..

  149. hairul azami October 14, 2010 at 10:50 pm #

    so, by using iframe base, we can make it simple application isn’t it?

  150. Jayesh October 15, 2010 at 2:45 pm #

    Hi all,
    I have a problem when im trying to uninstall the app. I have a text box for email validation. I have option link by which user can renter the email id. As soon as user clicks on reenter link, the information related to user which I am saving in my DB should be deleted. Using REST API functionality is working fine. When turned ON GRAPH API unauthorizecall back is not working for me. I am checking for fb_sig_uninstall parameter, if it is found then delete users entry from DB. I suspect in GRAPH API, some different parameters are getting passed and I have no clue… Can anybody help me out….

  151. HASNAIN October 16, 2010 at 6:26 pm #

    Hi
    i am creating graph api and iframe base facebook canvas application with php sdk. i have a problem in invitation code i am using the following code but it works only in fbml i have read your tutorial about render fbml but but nthng seems 2 b working so any plz corect my code:

    /*Multiple Friend Invitaion*/
    $fql = ‘SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=”‘ .
    $userId . ‘”) AND has_added_app=1′;
    $_friends = $fb->api_client->fql_query($fql);
    // Extract the user ID’s returned in the FQL request into a new array.
    $friends = array();
    if (is_array($_friends) && count($_friends))
    {
    foreach ($_friends as $friend)
    {
    $friends[] = $friend['uid'];
    }
    }
    // Convert the array of friends into a comma-delimeted string.
    $friends = implode(‘,’, $friends);
    $content = ” has played ” . APP_NAME .
    and thought it’s so cool even you should try it out!\n” .
    “get_add_url() . “\” label=\”Play ” . APP_NAME .
    “\”/>”;
    ?>
    <fb:request-form action="?act=done" method="post" type="” content=””> <fb:multi-friend-selector actiontext="Here are your friends who don't have yet. Invite whoever you want -it’s free!” exclude_ids=”” />
    <?php
    /*Multiple Friend Invitaion END*/

    and i forget to mention that your tutorials are always been wonderful.

    • mahmud ahsan October 16, 2010 at 10:40 pm #

      Please learn the basic rules to render FBML in iframe or FBConnect base app. You have to load javascript-sdk so that the FBML code renders.

  152. Suryakant Kale October 19, 2010 at 7:17 pm #

    bookmark, height and add mail functionality. If we are integrating Bookmark functionality, add mail and publish to wall functionality are not working. If we are implementing add mail and publish to wall functionality, Bookmark and height are working.

  153. Filippo October 22, 2010 at 10:25 pm #

    Hi,
    thanks for this awesome tutorial!
    I have just one problem using the “invite friends” page: when the user clicks on the Skip button he’s redirected to the page http://www.connect.facebook.com/widgets/serverfbml.php.
    The same happens after he sends an invitation request.

    Moreover at the bottom of the invitation page appears this error:

    “serverfbml form action must be within the application’s connect url”

    Do you have any advice?

    Thank you =)

  154. Murvin Lai October 23, 2010 at 4:55 am #

    Thank you for the information. One thing I still have problem is that…

    In FBML, we can find out a user is logged in or not, using: $_REQUEST['fb_sig_logged_out_facebook']
    how to do it in iFrame with new graphAPI?

    The data return from parsing the signed_request are the same for logged out and logged In without installing the application.

    any idea?

  155. Selena October 23, 2010 at 6:32 pm #

    I try to use this code in my application, it shows dialog, but i can’t close it. Any idea?

    function show_dialog( title, message ) {
    FB.UIServer.Methods["fbml.dialog"].size = {width:280, height:60};
    FB.ui({
    method:’fbml.dialog’,
    display: ‘dialog’,
    fbml: (
    ”+
    ”+title+”+
    ”+
    ”+message+”+
    ”+
    ” ),
    width: ’280px’,
    height: ’60px’
    },
    function(response) {
    });
    }

  156. Matteo Benini October 25, 2010 at 7:54 pm #

    hi to everyone, i’m fallen into the infinite loop… code out of the box make it and i don’t know how to stop… i’ve found that is the $facebook->api(‘/me’) instructions that generate always an exception but i can’t find a solution…
    $_REQUEST and $session aren’t empty but $_REQUEST['session'] has a strange value!
    i’m working under snowleopard on a virtual server (MAMP) so i’ve set all the URLs as localhost:8888 except for the Site Domain field…

  157. Vinay Nishad October 27, 2010 at 1:45 pm #

    I just wanted to discuss …. can we have a pop up for the invite friends in iframe facebook application .

    Please revert me at your comfortable zone.

    Thanks,
    Vinay

  158. kiran October 28, 2010 at 11:04 am #

    I have created a facebook application http://apps.facebook.com/beer-beverages/. It has an image gallery and google map. Both are loaded on page load using javascript. I added the application in a facebook page tab but google map and gallery are not working. My page is located here: http://www.facebook.com/pages/Kiran-takeaways/149579291723154?v=app_154941544542752&ref=sgm

    Please advise how can i get the gallery and map working on application tab?

    • mahmud ahsan October 29, 2010 at 6:46 pm #

      You have to use FBJS to customize your code so that the gallery and google map shows in page tab. In page tab, currently normal javascript is not fully work. Facebook uses their own customized FBJS

  159. Jan October 30, 2010 at 8:28 am #

    Is it possible to (if it is – how do I) make a form post to the db (eg. a choosen image) and send the along with the invite friend function..?

    • mahmud ahsan October 30, 2010 at 12:44 pm #

      As far as I know, its not possible.

      • Jan October 31, 2010 at 5:01 am #

        It was late last night. I can see, I did not explain it correct. I want to post to the db and send a invititation at the same time.. Not send the item with the invitation… :/

  160. jan November 1, 2010 at 5:21 am #

    Good article! is there any way to upload status text with image, without doing a photo.upload, and not using an external image link? meaning, i have a local image file that i would like to post as status with text and action links. thanks for the help.

  161. SoMeOnE November 2, 2010 at 1:12 pm #

    Thanks
    Very good articles!
    I have a question.
    Perhaps with the help of publish messages on friends wall (as if that would be another sign on the wall came out that I wrote it).

    Such a code
    $ result = $ facebook-> api (‘/ friend_id/ feed /’, ‘post’, $ attachment);

    represented as js sdk.
    Thus
    FB.ui(
    {
    method: ‘stream.publish’,
    message: ”,
    attachment: {
    name: name,
    caption: ”,
    description: (description),
    href: hrefLink
    },
    action_links: [
    { text: hrefTitle, href: hrefLink }
    ],
    user_prompt_message: userPrompt
    },
    function(response) {

    });

    only not me wall. friends wall.

    as this application
    http://apps.facebook.com/magicboxapp/posttofriendswall.php

    thanks.

  162. hansihe November 3, 2010 at 2:44 am #

    I get this:

    Exception Object
    (
    [message:protected] => Facebook needs the CURL PHP extension.
    [string:Exception:private] =>
    => 0
    [file:protected] => /var/www/kick/facebook.php
    [line:protected] => 4
    [trace:Exception:private] => Array
    (
    [0] => Array
    (
    [file] => /var/www/kick/fbmain.php
    [line] => 15
    [function] => include_once
    )

    [1] => Array
    (
    [file] => /var/www/kick/index.php
    [line] => 2
    [args] => Array
    (
    [0] => /var/www/kick/fbmain.php
    )

    [function] => include_once
    )

    )

    [previous:Exception:private] =>
    )

    I installed php curl. Any ideas?

  163. kamran November 4, 2010 at 4:09 pm #

    well actually im a new bie this code is really helpful but im suffering with this error will u tell me how I overcome on it.

    Additionally, a 404 Not Found error was encountered while trying to use an Error Document to handle the request.

  164. Hairul Azami November 10, 2010 at 12:26 am #

    hi Mahmud, Can we publish the wall to the fan page without API Key / without making an application?

    thank you

  165. waka November 10, 2010 at 11:10 pm #

    hi Mahmud, can u please help me.. i’m trying to do a wall post from my facebook app for days now and no luck getting it to work, can u please help me.. thanks!!

  166. Güray November 12, 2010 at 6:43 pm #

    Thanks for the great tutorial. But i didnt one thing in iexplorer.
    problem picture: http://img585.imageshack.us/img585/5338/sorun.png
    when i click home link or invite or another. The page redirect to facebook.com/login.php?apikey=blablabla….. everytime.
    i want to do yours. Thank you in advance.

  167. Marco November 17, 2010 at 11:41 pm #

    Hi Mahmud, i dont know if this is the right post to aski this question but here i go:

    I want to publish to the feed of my users with the following

    $status = “Message to display in the feed”;

    $statusUpdate = $facebook->api(‘/’.$fbme['id'].’/feed’, ‘post’, array(‘message’=> $status, ‘cb’ => ”));

    when I do this, the message is posted in the wall but also the status of said user is changed as well, I dont want to change the status of the users, just to post in the wall. I alredy tried removing the status_update permission but still is being updated. I haven’t found a way to publish only to the wall. I hope you can help me. Once again thank you for all the useful information you provide to us.

  168. lea November 19, 2010 at 5:43 pm #

    hi, ive try and dowload ur code and it cannot works..it says

    Sorry, something went wrong.

    We’re working on getting this fixed as soon as we can.

    Go Back

    is it fb bugs or did i do something wrongs?..

  169. Hamxa Kazi November 20, 2010 at 1:40 am #

    heyy thanx for the awesome info this is the best written tutorial on the web for fb dev. but please help me with this problem … i want to post the feed on the user i select not my own so what do i do … for example like the application social interview posts a feed on the wall of the user selected.. plz urgent help needed

  170. Mike November 20, 2010 at 9:18 am #

    First . . .best tutorial I have found and has really launched progress on my first app.

    Here is my problem and I hope someone can help. I am using this tutorial exactly, and everything is working. However, I need to be able to control the height of the iFrame so there is no scrolling and the page will expand to fit my content.

    Any clues . . . I am a newbie, so please be specific.

    • Steve H November 26, 2010 at 4:07 pm #

      Mike – have you found a solution to this yet? I am having the same issue.

  171. Berger November 22, 2010 at 3:20 pm #

    Hi,
    First of all this article is great!!

    But i have a little problem.
    I took all files in your zip and put them in the server but the application doesn’t run.
    It seems like it stuck in some infinite loop.
    I did anything said in the article beside stting the Connect URL which doesn’t apear in my facebook.
    What should i do to make this app run?

    thank you!!!
    Berger

    • Benyamin Ragil November 22, 2010 at 3:28 pm #

      Hi Berger,
      I had the same problem about a month ago. At that moment, the problem was the CURL and the JSON encode is not installed properly on my server (i’m using shared server). I contacted the server admin and asked him (nicely) to check the CURL and JSON component. He checked that 2 items and now everthing is working.

      • Berger November 22, 2010 at 3:45 pm #

        So what do i need to define in my application properties beside “Canvas Page” and “Canvas URL”?

        I saw that facebook takes my index.php file from the folder i defined. But in the example above – I need to put all 7 files in that folder? What are all the directories in the zip file?

        thank you again,
        Berger

        • Benyamin Ragil November 22, 2010 at 3:56 pm #

          Hi,
          Please check for the CURL and JSON installation in your server. As far i know, the apps will not run without those components installed.

          thanks.

  172. Bishwajeet November 22, 2010 at 4:09 pm #

    How to put that invite.php page inside the jquery tabs using ajax ?

    I have tried a lot but that invite page in not getting loaded using ajax, other pages are working fine

  173. Steve H November 22, 2010 at 7:22 pm #

    Firstly, I would like to say a big thank you for this tutorial and code. It really helped to get me started. As all new FB apps will be using oAuth, this site is the only one with useful information. Thanks!

    However, I am having difficulties extracting and storing the oAuth information into a MySQL database using PHP. I thought I understood how it works, but I always end up with errors! I also cannot work out how to get ANY of the extended properties.

  174. Shaarawy November 26, 2010 at 7:26 am #

    Hi, how can I get 5 active users to be able to submit my app to the facebook application directory?. I have sent the link to my friends and they able to open it but the active and total users count still zero. please help me

  175. jasmine November 29, 2010 at 10:04 pm #

    Awesome tutorial!!
    But whey the invite doesnt render in ie7?
    And data couldnot be inserted to database. There is no problem in other browsers!

  176. udop December 2, 2010 at 2:19 pm #

    Hi,
    I have a problem. I tried to check and understand the great example. When I try it as demo everything runs great, but I can’t see my profile_pic. When I try to use it in my app, I get the user information, but when i click on “invite” or “home” I get the 403 Error “access denied” . I don’tknow, what I could do.
    Regards, Udo

  177. phpExe December 3, 2010 at 1:46 pm #

    In invite section, in internet explorer :
    http://apps.facebook.com/thinkdiffdemo/invite.php?session=xxxxsession_keyxxxxx

    Application doesnt redirect to index and not doesnt insert anything to database in ie. But there is not any problem in other browsers. Is there any solution for ie problem?

    • AlexG December 3, 2010 at 2:38 pm #

      I have the same issue in Internet Explorer. The invite section of this example doesnt work in IE and Opera browser. Everybody is having this issue?
      How did you fix it?
      Thanks guys

      • phpExe December 4, 2010 at 11:28 pm #

        AlexG;
        I couldnt find any solution. I have asked about this issue in facebook developers forum but there is not any solution yet.

  178. joinpaintball December 3, 2010 at 2:21 pm #

    Hi!

    Is there any way to run a php based facebook api in a atb of a fan page?

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

      you can use php sdk for some tasks in tab page application. But its a kinda different than iframe app.

  179. joinpaintball December 3, 2010 at 2:22 pm #

    Sorry i made mistake in my former comment.

    ATB = TAB!

    thx

  180. Junaid December 4, 2010 at 1:26 am #

    m getting the infinite loop issue.. is ther some proper solution for it yet??

    i tried solution from alon 21st june, but no luck..

    Thanks

    • naokikun December 6, 2010 at 12:30 am #

      I have the same infinite loop problem.
      I’ve managed to get it work by using the lastest facebook.php and fb_ca_chain_bundle.crt from http://github.com/facebook/php-sdk/

      Hope this help you too.

      • Dale Biagio December 31, 2010 at 3:09 pm #

        Thanks so much that helped me too!

  181. Martin December 5, 2010 at 2:35 am #

    Thanks for this awesome guide! I think Facebook should employ you to do their docs!

  182. Jayesh December 6, 2010 at 6:31 pm #

    HI Mahmud.
    I want to count how many shares and likes were done through my postings. Suppose I posted some thing on my wall, my friends clicked and shared, my friends friend, his friends etc . So is it possible to get the count for my facebook id, how many users clicked and shared that same posting? Is it possible using graph api. I need individual stats and not total? reply to this posting will be apreciated.

    Thanks

  183. Cristian December 7, 2010 at 2:18 am #

    Hi Thanks for the example I am doing very well
    a question is this example is acceptable to us facebook its approval, or is no longer acceptable?

    Sorry for my English
    Thanks

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

      Sorry I don’t understand your question, if you want to show your app in facebook application category you’ve to submit your app in there.

      • Cristian December 7, 2010 at 4:16 pm #

        In facebook documentation
        I get this poster

        Please note: We are in the process of deprecating the REST API, so if You are building a new application you shouldn’t use this function. Instead use the Graph API and access the User object.

        If I use FQL My application will be rejected?

        Thanks

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

          Deprecated doesn’t mean rejection. Facebook will completely ban REST api much later (*my guess). And if they completely ban REST they will provide alternative way to call FQL and other REST api methods.

  184. Ben December 10, 2010 at 4:04 pm #

    I totally agree with Martin; your tutorial helps so much more than the actual FB documentation. Thanks!

    I’ve got everything working except one thing: iframe resizing. Facebook seems to have changed some stuff about that and I read it should work with something like:

    window.fbAsyncInit = function() {
    FB.Canvas.setAutoResize(91);
    }

    This doesn’t do anything.. I know a lot of people have problems with resizing the iframe. Have you got a solution?

    • Steve H December 12, 2010 at 4:10 am #

      Resizing the iframe gave me a lot of problems. However I have found code that works…. Make sure that the code is inserted immediately after the tag and that the second half is the last code before the tag.

      FB.init({
      appId : ‘your app id here’,
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml : false // parse XFBML
      });
      FB.Canvas.setAutoResize( 100 );

      … the rest of the page body goes here …

      FB.Canvas.setAutoResize( 100 );

      • Ben December 12, 2010 at 4:50 pm #

        Thanks Steve!

    • Steve H December 12, 2010 at 4:22 am #

      Ok given up trying to paste code here – found the original posting that shows the code. http://stackoverflow.com/questions/4150459/iframe-based-facebook-app-gets-unwanted-scroll-bars-with-a-smaller-windows-size

  185. djemmers December 10, 2010 at 4:29 pm #

    what a GREAT tut! indeed much better then the FB documentation!!!

    I need to create an application that auto posts new links (from a mysql database on my server) to the wall of the users of the application.

    any idea where I should begin?

    • djemmers December 10, 2010 at 4:32 pm #

      I should specify,
      it should appear in their newsfeed.

      greetings

  186. breteuil December 10, 2010 at 11:14 pm #

    Hi there,

    I’ m using your code which is working great.
    Problem comes in one of my php script where I’m using session_start(); and it does not get set at all…

    Do you have any example code I should use to find a turnaround?

  187. Hasnain December 11, 2010 at 12:10 pm #

    Hi, i have created this application http://apps.facebook.com/demo_application_one/. i am using .xml file to store questions and answers. i want to prompt user to publish the results of this quiz, i know how to use stream publish but don’t know how to pass parameters so that the results will be displayed. So please help me anyone.

  188. Vinod December 14, 2010 at 11:20 pm #

    In step 8, how do i write multi line or bulleted data??

  189. Two December 17, 2010 at 2:10 pm #

    Hello Mahmud, Thanks for the great info. One question.
    GetSession() returns NULL on Ajax.php callback for status update in updateStatus().

    Example code all works fine – FQL call returns correct dat and
    updateStatusViaJavascriptAPICalling() works.

    The problem is that
    ajax.php fails during the testing of $session when it includes fbmain.php.
    Anyone understand why getsession() would fail this way?
    It works once when app loads, and then fails on second call?

  190. Kunal December 20, 2010 at 11:05 pm #

    It was again to easy to understand this article, like others written by you (some of which I have read).

    I want to know regarding Invitations. Like the method mentioned here, a user can invite his/her friends. What else can be done by using request-form.

    I was wondering if it is possible to do the following:

    I have a form, user writes something in it or there is some default text in that box.
    Now below this, there is this request-form where a user can see all his friends.
    Now, he selects say 2 friends.
    Then this default text gets posted on wall of these two friends (instead of invitation).

    So, what I want is that: There is a message and a user can post it to multiple friends (the same message) in one go.

    Is this possible by using request-form.

  191. Tony December 20, 2010 at 11:16 pm #

    Hi there mahmud, many thanks for this and all of your other excellent tutorials – I think someone else already said above, you should be writing FB docs cos the stuff they have is well…. hopeless by comparison to yours.

    So anyway, quick question, have been following all of your tutorials and things are going great so far – problem I now face is that I have and xfbml FB:like button to the header of my page – part way thru I have an FQL call to see if the user of this app has already liked an associated fan page, if they have already liked they see portion X, if they havent liked yet they see portion Y – that too works great, but currently it needs a manual refresh before getting from X to Y. So am trying to add an event listener – it sort of works but is throwing a Firefox pop up asking to resnd info before it refreshes. Have load java sdk like so and added event:

    FB.init({appId : ”, status : true, cookie : true, xfbml : true});
    FB.Event.subscribe(‘edge.create’, function (response) {window.location.reload();});

    The app is here: http://apps.facebook.com/marqueenightclub/

    The ideal workflow I’m trying to re-create would be the same as this:
    http://apps.facebook.com/menexpertwhiteactiv/

    any help would be much appreciated and once again many thanks for ALL of your great tutorials :)

    Regards Tony

  192. Tony December 20, 2010 at 11:19 pm #

    PS, for some reason the appid part didnt print in above code but its using your $tring fbconfig appid

  193. venkatesh December 21, 2010 at 12:27 pm #

    Hi
    am new to the graph api of facebook.
    i want to use this api to get public data on facebook. i dont have website. i want to do this with coding in java. and store in a database. how can i do it..

  194. bashir December 22, 2010 at 4:21 pm #

    Actually your tutorial is best…

  195. mukund December 23, 2010 at 2:58 am #

    Thanks a lot..
    Nice tutorial for beginners..

  196. प्रसाद गुप्ते December 25, 2010 at 12:25 am #

    Thanks a lot for this! Works like a charm on my server, but doesn’t show up within the FB window :(

    ///////////////
    Application temporarily unavailable
    Runtime errors:

    fb:iframe: URL has been explicitly blocked
    ///////////////

    Sorry, the application you were using is experiencing a problem. Please try again later.

    Try: http://apps.facebook.com/wish-em-well/

  197. MARC December 25, 2010 at 5:20 pm #

    Hi ! Al last a web page that really help beginners !
    Congratulations !!

  198. bashir December 26, 2010 at 2:21 pm #

    Hi your tutorial is so good which i cannot expressat this moment.
    I have a problem that after invitation or skip invitation, I want to back in my home page but here blank page is come.
    So how I can redirect my page in my home page….
    Please inform me in my email address…

    Best regards
    Bashir

    • mahmud ahsan December 27, 2010 at 4:34 pm #

      Hello, you’ve to provide the page link here

      <fb:request-form
                          action="http://yoursite.com/yourpage.php"
      
      • bashir December 27, 2010 at 5:14 pm #

        Thanks a lot ..

  199. Jayesh December 27, 2010 at 1:01 pm #

    Hi Mahmud,
    I am trying to use action links using graph api. For all its working with the PHP code. I am using vb.net code. I am not able to use action links using GRAPH API. Can you help me??? .. :(
    Reply to this email will be highly appreciated…..

    Thanks in Advance.

  200. Awais Qarni December 27, 2010 at 6:31 pm #

    hi man. you have done nice work. I have used your code for extended permission
    $session = $facebook->getSession();
    $loginUrl = $facebook->getLoginUrl(
    array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘email,publish_stream,status_update,user_birthday, user_location,user_work_history’
    )
    );

    $fbme = null;

    if (!$session) {
    echo “top.location.href = ‘$loginUrl’;”;
    exit;
    }
    else {
    try {
    $uid = $facebook->getUser();
    $fbme = $facebook->api(‘/me’);

    } catch (FacebookApiException $e) {
    echo “top.location.href = ‘$loginUrl’;”;
    exit;
    }
    }
    it works fine when user comes first time on the application. once he authorize application, I can access all data related to extended permission. But problem is that when I add some new extended permission and user again comes to my application, no pop up having asking user for permission is shown. and I am unable to reterive the data related to newly added permission. Can you tell me the exact problem?

  201. praveen December 29, 2010 at 11:48 pm #

    Thank you soooooo much

  202. bashir December 30, 2010 at 12:47 pm #

    I have a quiz application in facebook plateform which name is Are You Really in Love?.
    I want to publish result in the news feed after complete the quiz.Please give this code or give suggest to me which is perfect to me.

  203. Cristian December 30, 2010 at 5:05 pm #

    Hello
    How to show a list of users who have already accepted my application?

    • mahmud ahsan December 31, 2010 at 9:48 pm #

      When first time user authenticate your application you should save his Facebook UID in your database to track user list.

  204. Kelly December 30, 2010 at 6:58 pm #

    hi.. I am using your code quite a bit in my applications.

    in one application i already have about 2000 users. and i have added functions to allow them to post pictures to an album.

    I have had to request additional extended permissions, which works find if the user has never authorized my app. however if they already have used it, it does not ask them for the additional permissions.

    How can i adjust the FBmain.php file to see if they have all the required permissions approved?

    $session = $facebook->getSession();
    $loginUrl = $facebook->getLoginUrl(
    array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘email,publish_stream,status_update,user_birthday, user_location,user_work_history’
    )
    );

    • Awais Qarni December 30, 2010 at 7:02 pm #

      Kelly I am having the same problem. I have also posted this problem but no body has answered…..

    • mahmud ahsan December 31, 2010 at 9:35 pm #

      You can provide additional permissions in ‘req_perms’.

      • Awais Qarni January 1, 2011 at 10:56 am #

        Sorry Muhammad Ahsan I think you didn’t understand the question or you didn’t read it carefully………

  205. bashir January 4, 2011 at 12:42 pm #

    I have a IFRAME base quiz application in facebook plateform. I want to publish result in the news feed after complete the quiz.Please give this code or give suggest to me which is perfect to me.

    mbu

  206. clark January 4, 2011 at 2:04 pm #

    Excellent website.This is very informative..
    Thanks.
    facebook connect applications

    • Thrik January 5, 2011 at 5:59 pm #

      Hello,
      Thank you very much for post. There is small bug in this application. If the user goes to your application for the first time, request for permission dialog comes and if the user clicks on “don’t allow” it redirects to same page again and again.

  207. Ivan January 5, 2011 at 12:09 pm #

    Excellent example. Thanks.

  208. Federico Noto January 5, 2011 at 1:24 pm #

    Hi Mahmud Ahsan.
    First i thank you for the tutorial. I use in an app and work very well.
    But today is not workinkg. Can i do a question:
    How i must configure the new advanced facebook options for its work?
    Thanks again, and sorry for my bad english :)

  209. hached January 5, 2011 at 9:36 pm #

    salam alikom,
    thanks for you tuto, i have test it for the first time today, but it not working, i think there is some think changed in facebook SDK,

    • mahmud ahsan January 7, 2011 at 10:00 pm #

      I’ve just tested and found everything is working nicely.

  210. ashwin January 6, 2011 at 6:02 pm #

    Hello,

    Can we use a combination of ajax and javascript to show the invite friends code in the dialog, such that we do not have to redirect it to a php page. Any suggestions.

    thanks
    ashwin

  211. Aaron January 8, 2011 at 3:50 pm #

    Hi, thanks for providing the code, its a great reference point. I keep getting redirected to the login screen everytime I try to visit the app even though I am already logged in. Any ideas? Thanks

  212. Robin January 8, 2011 at 3:54 pm #

    Hey mahmud,

    firstly mighty thanks for the wonderful write-up.

    is there way to post a message on the wall when I invite a friend using the above invitation feature code.

    I want to post a message like ” You have an game request from xyz”. Please visit “www.facebook.com/games” to accept the invitation.

    Thanks in advance, hoping to see a reply

    Cheers

  213. Enderson Moderno January 9, 2011 at 1:04 pm #

    The best! Thank you!

  214. Pino January 12, 2011 at 3:52 pm #

    Mahmud, your’re the man!

    The “Stream pubblish” of the given demo does not work for me. I get “FB is not defined” in FF’s Error console (the same in Chrome’s Javascript console). Am I alone with this issue?

    • Pino January 12, 2011 at 6:52 pm #

      I figured it out. The problem were some ad-blocking browser plugins. Works now.

    • mahmud ahsan January 13, 2011 at 1:50 am #

      I just checked my application http://apps.facebook.com/thinkdiffdemo/ and stream publish is working nicely.

  215. hohesc January 13, 2011 at 9:47 pm #

    Greate Guide! Thanks! Helped a lot, created my first app yesterday ;)

    For those who want to publish Photos using Graph API, you need to set ‘fileUpload’ => true when creating the App instance (eg. line 24).

    Then you can do it like this:
    $args = array(‘message’ => ‘your message’);
    $args['image'] = ‘@’ . realpath(‘qwertz.jpg’);
    $p1 = $facebook->api(‘/ALBUM_ID_HERE/photos’, ‘post’, $args);

    It took me some time to find this solution.

  216. kalel January 14, 2011 at 12:43 pm #

    Great demo app! Thanks =)
    I’ve tried your app and had set up another, using the same source files (i just modified the appid, secretkey, etc). Everything works fine except the publish stream feature. I encountered this error when trying to publish (in IE 7,8) :

    An error occurred with phpsdktest. Please try again later.
    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.

    However, this seems to work perfectly in Chrome and FF. In safari, the error is intermittent.

    I’ve done a bit of a research and tried the steps that some have suggested, like adding P3P header. But still, it doesn’t work for me.

    I don’t have any idea why such a scenario happens. Any thoughts on this?

    Thanks in advance,
    K

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

      Is the same error showing for my app in IE also. by the way I use mac.

  217. Rick January 17, 2011 at 12:12 am #

    Great page.

    What if I want to send POST data to my server but ALSO want to ensure the user is logged in to facebook? It seems that I can’t get both the signed_request and my POST data to all work at once in the iframe. Any ideas?

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

      You can use ajax to post data in your server.

  218. Ed Ayvazyan January 17, 2011 at 3:50 am #

    Thanks for the article!
    Please, note, the demo application has an XSS vulnerability, i.e, you may execute arbitrary php code on the server and steal any sensitive data by just replacing the “page” argument in the with an url of the code you wish to execute.
    Please, fix it by simply searching for the requested file on the filesystem. Thanks

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

      Brother, when i wrote this code I added a special logic, so you can’t read other php using this file from my server. so you can’t XSS. :) Wanna check try it yourself.
      in the template.php i coded:

      <?php
              if (isset($page)) {
                  if ($page === 'invite.php' || $page === 'home.php')
                  include_once $page;
              }
          ?>
      

      This is called whitelist checking.

      • Ed Ayvazyan January 17, 2011 at 11:19 pm #

        Great, but this looks to be a later fix.
        I’ve downloaded the package yesterday, and in my version of the template.php there is just:

            <?php
                if (isset($page)) {
                    include_once $page;
                }
            ?>
        

        And I’ve set it up and tried and I could exploit it
        Please, update the downloadable version
        Thanks

        • mahmud ahsan January 18, 2011 at 12:34 am #

          Yeah I know, I didn’t included that code in the zip file. Because this is a tutorial and people should research a bit of code.but now i think i should update in the zip too because i found some people directly copy paste and use this app.

  219. Eldy January 17, 2011 at 5:18 am #

    Publish stream error for me. my link showed a windows : “An error occurred. Please try again later.” instead of the publish stream box.. I wonder..

Trackbacks/Pingbacks

  1. Please give some life to this section too - November 22, 2010

    [...] this link ,It is excellent tutorial according to me,It will give you a brief idea of facebook API Graph API & IFrame Base Facebook Application Development | Thinkdiff.net Just go through it and reply here asap I need to develop this application as soon as possible so [...]

  2. CE Facebook Application - November 23, 2010

    [...] this link ,It is excellent tutorial according to me,It will give you a brief idea of facebook API Graph API & IFrame Base Facebook Application Development | Thinkdiff.net Just go through it and reply here asap ,so that we can final aim of this application then move to [...]