Graph API & IFrame Base Facebook Application Development

Posted by mahmud ahsan on May 28, 2010 in FB Connect, Facebook | 204 Comments

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/
Download Code

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:

Related Posts

If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!)

Comments (204)

 

  1. Nivas Sivanadiyan says:

    Very nice, Useful …

  2. shaon says:

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

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

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

  5. zach young says:

    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 says:

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

      • zach young says:

        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 says:

          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 says:

            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.

  6. goldfuz3 says:

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

    Thanks!

  7. kevin says:

    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 says:

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

    After I modify your code will face problem.

  9. BEN says:

    i try to download your code but :

    Not Found

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

  10. IlexN says:

    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. 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 says:

    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 says:

      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>
      
  13. babyking says:

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

    • mahmud ahsan says:

      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 says:

    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 says:

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

    • sneakyimp says:

      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 says:

      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 says:

    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 says:

      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 says:

        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. Benson says:

    Thank you … all you code work so well …

  17. ilker says:

    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.

  18. Sparrow says:

    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…

  19. nasyarobby says:

    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 says:

      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>
      
  20. Adam Fordham says:

    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

  21. Henry says:

    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?

  22. eka says:

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

  23. Henry says:

    I solved the problem , here is the code

    if (!$session) {
    		$newString = str_replace("https","http",$loginUrl);
            echo "top.location.href = '$newString';";
            exit;
        }
    
  24. Javed Nazir says:

    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

  25. Stas says:

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

  26. ccarrasco says:

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

  27. danbe says:

    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

  28. chumzz says:

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

  29. miss geje says:

    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

  30. golow says:

    Thank you soooo much :D

  31. sisira says:

    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.

  32. ilk says:

    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

  33. Michael Gaigg says:

    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…

  34. Carol X says:

    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. says:

      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.

  35. Ian says:

    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.

  36. Dave says:

    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?

  37. rutherford says:

    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 says:

      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.

  38. Gary Danko says:

    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?

  39. Alfred says:

    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! :)

  40. Syed says:

    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:)

  41. alon says:

    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.

  42. Ghido says:

    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…

  43. Ian says:

    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?

  44. Emmanuel says:

    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

  45. alon says:

    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.

  46. alon says:

    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.

  47. DanielJ says:

    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?

  48. dhanasekar says:

    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.

  49. snail says:

    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 says:

      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 says:

        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?

  50. Anzorf says:

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

  51. snail says:

    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?

  52. Umair says:

    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:-)

  53. Ann says:

    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

  54. Nyong Grandong says:

    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

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

  56. Juan says:

    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 says:

      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.

  57. David says:

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

    Thank you!

  58. Mick says:

    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

  59. Peyote says:

    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 :)

  60. Ghido says:

    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 says:

      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!

  61. nish says:

    hi, when i tryed this i get error:

    HTTP Error 403.14 – Forbidden: Directory listing denied.

    I am stuck help me plz…

  62. tiffany says:

    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 says:

      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 says:

        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 says:

          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.

  63. tiffany says:

    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 says:

      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 says:

        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.

  64. joe says:

    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.

  65. Vishal says:

    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 says:

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

      • Vishal says:

        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 says:

          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 says:

            Vishal,

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

            Thanks,
            Venkat

  66. Joe says:

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

    • mahmud ahsan says:

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

      • Joe says:

        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

  67. Jonas says:

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

  68. Gianluca says:

    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!

  69. Shanavas c says:

    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

  70. Rico Chen says:

    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 says:

      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.

  71. Roger says:

    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 says:

      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 says:

        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

  72. kimou says:

    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

  73. kimou says:

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

  74. Mick says:

    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

  75. Hirklins says:

    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!

  76. Robin says:

    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.

  77. Matt Rouse says:

    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.

  78. akaayy says:

    Is this tutorial applies to FBML method??

  79. akaayy says:

    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~

  80. Dondie says:

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

  81. Dondie says:

    not working please help

  82. akaayy says:

    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] =>
    [/code] => 6
    [file:protected] => /var/www/html/facebook.php
    [line:protected] => 511
    [trace:private] => Array

    .....
    ......
    .......

    how can I solve this problem?

  83. Vishal says:

    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

  84. Dondie says:

    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

  85. Dondie says:

    please help me

  86. Birkoff says:

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

  87. havanakoda says:

    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 ?

  88. Peyote says:

    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

  89. Vishal says:

    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 says:

      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?

  90. buzzknow says:

    really nice mahmud :)

    i learn a lot from u :)

  91. Kiko says:

    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.

  92. Dipen says:

    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.

  93. kipdrordy says:

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

  94. M.M.H.Masud says:

    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

  95. M.M.H.Masud says:

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

  96. kipdrordy says:

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

  97. joshul says:

    This example is not for graph api.

  98. Edwin says:

    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??

  99. chiemeka says:

    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″

  100. chiemeka says:

    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”

  101. Mark says:

    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

  102. konfus says:

    5. Form Submission technique and getting Data

    Not woriking in IE, $_POST is empty.

    Google Chrome and FF are fine.

  103. Shani says:

    Thank for this great tutorial.

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

    Thanks

  104. Deepesh says:

    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?

  105. Noirita says:

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

  106. @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;

  107. Dave S says:

    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… ?

  108. Dave S says:

    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.

  109. kipdrordy says:

    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?

  110. HASNAIN says:

    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.

Leave a Reply