Increase facebook iframe app’s performance


facebook This tutorial is for advanced facebook app developer. If you’re beginner than first learn about developing facebook application. Normally if you see iframe base or fbconnect base facebook application development using php sdk you’ll notice some authentication code.

In the example they will run that authentication code each time before page load. But if you look carefully you’ll notice that, the authentication code of php will take extra time to load the iframe base application. Now I’m going to describe how we solved such problem.

For example see the official documentation The authentication part of this code is:

$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

// login or logout url will be needed depending on current user state.
if ($me) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}

Normally you may think to include this part in all pages of your application.

  1. But do you really need this?
  2. Could we make any optimization here?

Yeap, we need this, coz we want to detect whether user is logged in facebook or not and whether user approved our application or not. But in a recent project I found each page of our application loads little slow. Because of these:

$facebook = new Facebook(array(
  'appId' => '254752073152',
  'secret' => '904270b68a2cc3d54485323652da4d14',
  'cookie' => true,
));

$session = $facebook->getSession();
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

Each time we call a facebook api via $facebook->api(‘/me’), and it takes sometimes 2~4 seconds to get the data. But we really not need this to call each time if we know user’s session is valid. But in the official document they said, if an api successfully called then it means we have a valid user’s session.

// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

But I created a technique by using that you could be sure that user has a valid session.

$facebook = new Facebook(array(
                'appId' => '254752073152',
                'secret' => '904270b68a2cc3d54485323652da4d14',
                'cookie' => true,
));

/*-------- MY Optimization Techqnique Start -------*/
if (isset($_REQUEST['session'])) {
    $session              =   json_decode($_REQUEST['session']);
    $uid                  =   $session->uid;
    return;
}
/*-------- My Optimization Technique End ---------*/
$session = $facebook->getSession();
//if here comes that means user hasn't a valid session
$loginUrl = $facebook->getLoginUrl(
       array(
        'canvas'    => 1,
        'fbconnect' => 0,
        'req_perms' => 'email,publish_stream, offline_access,sms, user_location'
        )
);

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;
    }
}

So look at the if logic if (isset($_REQUEST[‘session’])) If you print_r($_REQUEST), you’ll see each time facebook will send a $_REQUEST[‘session’] if user has a valid session. And this session object is a JSON encoded string. If user’s session is not valid, or user isn’t approved your application then when first time user visits your application facebook will not send this $_REQUEST[‘session’] object. So the above code will continue the normal procedure, but when the above code finds a session object then it just created a facebook object, and retrieve the user uid and return so that we skipped any additional facebook api calls.

The above solution makes our project to load faster. The project I am working is a NDA project otherwise I would mention the url.

Hope this technique help you. By the way, I haven’t mentioned any caching or optimization techniques here because those are separate issue to make application loads faster. I only mentioned here how to load iframe app faster bypassing facebook api call.

mahmud ahsan

Love computer programming and write occasional blog post. In my early career I worked mostly on web based application and since 2011, I exclusively working on iPhone and android applications. I work at home, father of a nice kid and husband of a beautiful wife. [My Business | Twitter | Linkedin]

You may also like

29 Comments

  • Jerzy
    July 1, 2010 at 12:09 am

    yep, it works but lines 9 and 10 should looks like:

    $session = json_decode( get_magic_quotes_gpc() ? stripslashes($_REQUEST['session']) : $_REQUEST['session'], true );
    $session = $this->validateSessionObject( $session );
    $uid =   $session["uid"];
    

    and should be fine, enjoy.. great blog btw

  • Ghido
    July 3, 2010 at 5:20 pm

    Hi, I have a problem with AJAX calls from my App.
    In the ajax.php file I included “fbmain.php”, so that it checks the session.

    Sometimes the AJAX call works and returns the expected value, but sometimes it does not find the session and tries to redirect to $loginUrl.

    So, instead to return the value, it returns top.location.href = ‘$loginUrl’;

    How can I have always a valid session in the ajax.php? Shall I pass the $_REQUEST[‘session’] to ajax.php?

    Thanks

    • mahmud ahsan
      mahmud ahsan
      July 3, 2010 at 7:55 pm

      If you pass $_REQUEST[‘session’] and if that works, then you can use it.

  • Jirka
    July 9, 2010 at 8:26 pm

    Hi, problem with this solution is that if I log out in a different tab of the same browser, the session is still set in $_REQUEST[‘session’].
    Your code does not care about this. Do you have any idea how to improve it? (I was thinking about it and it seems that I really need to call the api every time to avoid this).

  • elias
    July 28, 2010 at 1:40 am

    takes too long to load the page…

  • Aaed Kayal
    August 17, 2010 at 5:26 pm

    How can i use this for the Old Php Api , i have app developed by the old api , and i amtrying to speed up this process , can you help me please with that point ?

  • shani
    September 7, 2010 at 7:57 pm

    Hello,
    I’m using your code from here :
    http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development/

    to test this and it doesn’t seam to work.
    I print_r $_REQUEST and I don’t see a key named “session”.

    The closest things I see are :
    There is “fb_sig_session_key] =>… ” and
    [fbs_152068981470157] => \”access_token=….&expires=…&session_key=…&sig=…&uid=…\”

    Is there something I’m missing?

    Thanks

  • Ian
    October 20, 2010 at 11:43 pm

    Hi

    You refer to enhanced caching – maybe you could follow this blog up with how you would go about using caching with the Facebook object.

    Nice blog

    Cheers

    Ian

  • Ian
    October 21, 2010 at 12:32 am

    Yeah seems as though the REQUEST[‘session’] only shows on the first page after Auth – this is due to the parameter being in the URI

    So it will not likely persist

    Using the $_REQUEST[‘fbs_APPID’] seems the obvious choice as this persists.

    This is not in JSON format though so simply

    // Get the Facebook Session
    $this->session = $this->facebook->getSession();
    return;

  • Ian
    October 21, 2010 at 12:55 am

    Also with the above you probably want to add into the JS connect the below. This is because if the user removes the application – refreshes, they will not be redirected straight away to re-auth the applciation

    FB.Event.subscribe(‘auth.logout’, function(response) {
    window.location.reload();
    });

  • Theo
    November 4, 2010 at 7:06 am

    I have a website that plays embedded youtube video.. I have built an iframe page in facebook that opens my site and video inside a facebook profile successfully. What embedded video setup do you recommend for my site and FB page if I want mobie phone compatability for iPhone and symbian?

  • Shaarawy
    November 26, 2010 at 7:22 am

    Hi, can you pleas guide me on how to submit my app to the application directory. It keeps telling me that it needs 5 users or 10 monthly users to submit it. I sent the link to many friends and they can access the application but the stats page of the app does not show any active or total users count. can you please guide me what I should do

    • Genadijus
      January 11, 2011 at 1:57 pm

      @Shaarawy
      If you didn’t submit your app to app directory, your app still will work, just users will not be able find your app by name in app directory. And error you are seeing is exactly what you need to have to be able to submit your app.

  • Genadijus
    January 11, 2011 at 1:32 pm

    I assume you use this code in a function that is included into all pages. That’s why you used return statement in optimized code part.

    and inline code would be
    if (isset($_REQUEST[‘session’])) {
    $session = json_decode($_REQUEST[‘session’]);
    } else {
    $session = $facebook->getSession();
    }

  • bashir
    January 11, 2011 at 6:12 pm

    Assalamu alaikum mahmud vai

    I have a Quiz Application in the facebook Platform, I want to publish my quiz result in the news feed from a quiz application.The application is developed in IFRAME base.
    Please give me code or instruction to me.
    Please help me vai amar..
    Sorry for that.

      • bashir
        January 13, 2011 at 12:33 pm

        Dear mahmud vai
        thanks for your quick reply
        Actually i want to pass the value of a php variable in the message field, So that when i click publish stream the box will come with that result of a quize. E.g:
        function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
        FB.ui(
        {
        method: ‘stream.publish’,
        message: ‘want to publish $result to the message field’,
        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”);
        }

        How it is possible
        Please give suggestion.
        bashir

        • mahmud ahsan
          mahmud ahsan
          January 13, 2011 at 1:24 pm

          Its also very easy, provide another parameter in the function and pass value from php.

          • bashir
            January 13, 2011 at 3:52 pm

            Please see why I can’t get result :
            Anything wrong in the following code ?

            function streamPublish(name, message, description, hrefTitle, hrefLink, userPrompt){
            //var points = “”;
            // var tpl_data = {“points”: points};
            //var points = document.setTextValue(”);

            FB.ui(
            {

            method: ‘stream.publish’,
            display: ‘popup’,
            message: ‘{message}’,
            attachment: {
            name: name,
            caption: ”,
            description: (description),
            href: hrefLink
            },
            action_links: [
            { text: hrefTitle, href: hrefLink }
            ],
            user_prompt_message: userPrompt
            },
            function(response) {

            });
            }
            function publishStream(){

            streamPublish(“Result Publish”,”, ‘This is AWESOME. It just measured how to Calculate Your Real Love by using this application. ‘, ‘Checkout this Application’, ‘http://apps.facebook.com/lovelycal’, “Facebook Application”);
            }

          • bashir
            January 13, 2011 at 3:54 pm

            function streamPublish(name, message, description, hrefTitle, hrefLink, userPrompt){

            FB.ui(
            {

            method: ‘stream.publish’,
            display: ‘popup’,
            message: ‘{message}’,
            attachment: {
            name: name,
            caption: ”,
            description: (description),
            href: hrefLink
            },
            action_links: [
            { text: hrefTitle, href: hrefLink }
            ],
            user_prompt_message: userPrompt
            },
            function(response) {

            });
            }
            function publishStream(){

            streamPublish(“Result Publish”,”, ‘This is AWESOME. It just measured how to Calculate Your Real Love by using this application. ‘, ‘Checkout this Application’, ‘http://apps.facebook.com/lovelycal’, “Facebook Application”);
            }

  • bashir
    January 17, 2011 at 11:09 am

    Dear mahmud

    Thanks for you help to me.
    I have completed my problem.

  • jon
    February 3, 2011 at 10:26 pm

    hi guys , doas some body knows why when i load the http://apps.facebook.com/my_app/ i get a screen wich ask me to put my password? like there is some kind f block, and after i put my password it take me beck to facebook home page

    i use this code:
    <?php
    //facebook application
    //set facebook application id, secret key and api key here
    $fbconfig['code' ] = "";
    $fbconfig['code' ] = "";
    $fbconfig['secret'] = "";

    //set application urls here
    $fbconfig[''] = ""; //http://thinkdiff.net/demo/newfbconnect1/iframe;
    $fbconfig[''] = ""; //http://apps.facebook.com/thinkdiffdemo;

    $uid = null; //facebook user id

    try{
    include_once "facebook.php";
    }
    catch(Exception $o){
    echo '’;
    print_r($o);
    echo ”;
    }
    // Create our Application instance.
    $facebook = new Facebook(array(
    ‘id’ => $fbconfig[‘id’],
    ‘code’ => $fbconfig[‘code’],
    ‘cookie’ => true,
    ));

    //Facebook Authentication part
    /*——– MY Optimization Techqnique Start ——-*/
    if (isset($_REQUEST[‘session’])) {
    $session = json_decode( get_magic_quotes_gpc() ? stripslashes($_REQUEST[‘session’]) : $_REQUEST[‘session’], true );
    $session = $this->validateSessionObject( $session ); $uid = $session[“uid”];
    return;
    }
    /*——– My Optimization Technique End ———*/
    $session = $facebook->getSession();
    //if here comes that means user hasn’t a valid session
    $loginUrl = $facebook->getLoginUrl(
    array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ’email,publish_stream, offline_access,sms, user_location’
    )
    );

    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;
    }
    }

    function d($d){
    echo ”;
    print_r($d);
    echo ”;
    }
    ?>

  • koki
    February 28, 2011 at 9:25 pm

    I found a solution to create an iframe application without being a facebook developer . It’s very powerful:
    http://www.facebook.com/iframe.apps

  • vaishali
    June 6, 2011 at 3:50 pm

    hello friends,

    how can i use xml in facebook application instead of using json..

    plz help me

    thanks in advance

  • vijay soof
    June 10, 2011 at 4:46 pm

    great sir.

  • ppc.bz
    July 19, 2011 at 12:30 am

    Is there another way to do this with the 3.0 PHP SDK?

    • Rodrigo
      July 20, 2011 at 1:53 am

      Hey ppc,

      Try this:

      $facebook = new Facebook(array(
      ‘appId’ => ‘app’,
      ‘secret’ => ‘secret’
      ‘cookie’ => true
      ));

      $requestFace = $facebook->getSignedRequest();

      if(isset($requestFace[‘user_id’]) ) {
      //user is logged
      } else {
      // do autorization code, user is not logged
      }

  • subashbabu
    July 25, 2011 at 1:59 pm

    I have created iframe based facebook applications.the problem is that how to check in all the pages facebook user is login or logout?

  • Sébastien Courtès
    June 1, 2012 at 10:09 pm

    Hello,

    Thanks a lot !!! Your tip saved my life 🙂

Comments are closed here.

About Me

Hi I am Mahmud Ahsan. I Love computer programming and write occasional blog post. In my early career I worked mostly on web based application and since 2011, I exclusively working on iPhone and android applications. I work at home, father of a nice kid and husband of a beautiful wife. [My Business | Twitter | Linkedin]

Twitter Feed

Fanpage