Graph API & IFrame Base Facebook Application Development PHP SDK 3.0

facebookFacebook recently updated their PHP-SDK to version 3.0. This is a major change. So I decided to update some of my facebook related tutorials with updated code.

At first I want to tell you that, this post is the updated version of my popular post Graph API & IFrame Base Facebook Application Development . So if you never saw that tutorial I request you to visit that and learn the basic things specially facebook application setup. Also on that post I mentioned some important things regarding iframe, so in this post I’ll not mention them again.

So in this updated post we will learn:

  1. How to update facebook php sdk 3.0 library
  2. Authentication
  3. How to give extended permissions
  4. How to call graph api
  5. How to publish stream using facebook’s latest dialog system
  6. How to request/invite your friends and track them

Before proceeding:

Demo AppDownload Code

1. How to update facebook php sdk 3.0 library

First download Facebook’s php sdk and from the /src directory copy facebook.php, base_facebook.php and fb_ca_chain_bundle.crt to your project dir. Then download my codes from here, in this zip file you also get the php sdk libraries. Now click below image to know about the files functionality.


2. Authentication

In fbmain.php line number 23->77 you’ll see below code.

  • At first we include the facebook.php library.
  • Then we created a $facebook object
  • Then we check if there is a valid session for user by  $user = $facebook->getUser();
  • Then we generate login url with extended permission
  • At line number 62 we call graph api $user_profile = $facebook->api(‘/me’);    to check if session is valid or not. If we get result then user’s session is valid otherwise we set $user = null that means expired or timeout session.
  • If no valid $user found at line number 71 we redirect user to login/authentication page for our application.
$user            =   null; //facebook user uid
        include_once "facebook.php";
    catch(Exception $o){
        echo '<pre>';
        echo '</pre>';
    // Create our Application instance.
    $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,

    //Facebook Authentication part
    $user       = $facebook->getUser();
    $loginUrl   = $facebook->getLoginUrl(
                'scope'         => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'

    if ($user) {
      try {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
      } catch (FacebookApiException $e) {
        //you should use error_log($e); instead of printing the info on browser
        d($e);  // d is a debug function defined at the end of this file
        $user = null;

    if (!$user) {
        echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";

After user successfully authenticated our application facebook will redirect user to our callback url that we provided in the developer application setting. Facebook additionally pass a parameter named code=XXXX . But as this is a iframe application that runs inside facebook so we used a special code at line number 16->19. This code checks if there is GET parameter code is defined or not, if its defined then it redirects user to the facebook app url.

if (isset($_GET['code'])){
        header("Location: " . $fbconfig['appBaseUrl']);

3. How to give extended permissions

When you’ll generate the login url you’ve to provide extended permissions here. Previously the parameter named was ‘req_perms’ and now its ‘scope’.

 $loginUrl   = $facebook->getLoginUrl(
                'scope'         => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'

Checkout extended permission list from here.

4. How to call graph api

In fbmain.php line number 76, you’ll see how I called the graph api. Here $user is facebook user’s UID. To know more about graph api visit this page

//get user basic description
    $userInfo           = $facebook->api("/$user");

5. How to publish stream using facebook’s latest dialog system

In template.php line number 50->54 you’ll see the facebook’s javascript function. To know more about feed please visit here.

FB.ui({ method : 'feed',
                        message: userPrompt,
                        link   :  hrefLink,
                        caption:  hrefTitle

6. How to request/invite your friends and track them

So you want your user will invite his friends to use this application, and also you want to track to whom your user sends request. Also you want to check if that user is come from via request or not. In demo application click Send Request/Send Invitation to check the request dialog. In template.php line number 88 you’ll see this function.

function newInvite(){
                 var receiverUserIds = FB.ui({
                        method : 'apprequests',
                        message: 'come on man checkout my application. visit',
                 function(receiverUserIds) {
                          console.log("IDS : " + receiverUserIds.request_ids);

This function show a invite dialog and if user selects friends and sends invite, then in the response you’ll get all of user’s friends UIDs as a comma separated string. So if you use Firebug in Firefox, you’ll see console.log(“IDS : ” + receiverUserIds.request_ids); will print IDS: XXXX in the console of firebug. So if you want to track the friends IDS who received invitation, then parse receiverUserIds and save them in your mysql database.

If a user authenticate your application from invitation then his URL would be[app_name]/?request_ids=012345678910

So in fbmain.php line number 23->26 you’ll see below code. I just blank them you’ve to write additional code for tracking user.

if (isset($_GET['request_ids'])){
        //user comes from invitation
        //track them if you need

I hope this tutorial will help you for developing facebook application.


mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Github | Business | Twitter | Linkedin | Youtube | Instagram | 500px]

You may also like


  • dbKooper
    May 23, 2011 at 12:12 am

    Hi Mahmud,
    is it possible to send friend request to multiple id’s using
    FB.UI friends.add method say an array of 3 id’s?

    Another question:
    we can add facebook iframe app to facebook page,
    similiarly , Can’t we add a app page to user profile page so that user can just use app without being redirected and the app runs inside 520px iframe??

    waiting for your answers!!!

    • mahmud ahsan
      mahmud ahsan
      May 23, 2011 at 3:09 pm

      Answer of your first question, I didn’t try it so don’t know, I think you should try by giving comma separated list of friends ids and if it fails then you could try json array of friends ids in there. Answer of your 2nd question, I think this is not possible.

  • Mauro
    May 23, 2011 at 7:28 pm

    Hello there Mahmud!

    Thanx for shareing this example… i want to get offline_access from users… how can i get the access token that i will need to do this when they are not connected to facebook?

    Thanx in advance!

    • mahmud ahsan
      mahmud ahsan
      May 24, 2011 at 12:19 am

      In the post I’ve shown a part where you can provide extended permission.

  • Matheus Jenevain
    May 23, 2011 at 9:23 pm

    Your articles about Facebook helped me a lot man!
    God bless you \o

    • mahmud ahsan
      mahmud ahsan
      May 24, 2011 at 12:20 am

      Thank You. I wish to publish regular post, but for my work I can’t manage time and so can’t publish regularly :S

  • Imran Athar
    May 24, 2011 at 3:25 am

    Hi Mahmud
    i am hanged our some issue i just want to post sum things on fan page in offline session.. i have go through ur old demo post but still i am facing alot of issues in getting the persmisiions or session id could you please upload the demo api to do that task plz…

    Imran Athar

  • Ivan
    May 24, 2011 at 12:11 pm

    Hi Mahmud,
    Great tutorial. I’ve just read it for the first time now and finally I have something to work with. Total noob here 😛
    Is it possible to make a form and provide the user with an option to select only one friend, for a referal programme? I’d then like to get this data: user’s name and his friend’s name, stored somehow or sent via e-mail to me.

  • Radek
    May 24, 2011 at 1:15 pm

    Easier way to redirect after authentication

    $loginUrl = $facebook->getLoginUrl(
    ‘scope’=> ’email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown’,
    ‘redirect_uri’ => “$fbconfig[‘appBaseUrl’]”

    • mahmud ahsan
      mahmud ahsan
      May 24, 2011 at 3:02 pm

      It will not work, as appBaseUrl contains, i tried that before i write this post.

      • Radek
        May 24, 2011 at 3:05 pm

        It works :), i test it and it works, the appBaseURl=

        These reditect into facebook application page.

        • dg
          May 29, 2011 at 1:13 am

          did not work for me…got this error:

          API Error Code: 191
          API Error Description: The specified URL is not owned by the application
          Error Message: Missing redirect_uri parameter.

          • dg
            May 29, 2011 at 1:24 am

            oops…had uri instead of url……

            still does not redirect to correct location.

            Just gose to blank page

  • rogerio
    May 24, 2011 at 9:05 pm

    once again your tutorials save my day.


  • Orlando Anaya
    May 24, 2011 at 10:06 pm

    Great tutorial. Much less confusing than the examples I found on Facebook Dev site. You made my day! Saved alot of hair pulling and cussing. Thanks a million! BTW– What widget did you use in dreamweaver for tabs???

    Thanks AGAIN!

    • mahmud ahsan
      mahmud ahsan
      May 25, 2011 at 12:14 am

      I don’t use dreamwaver, I use NetBeans IDE. And those tabs are from jQuery UI.

      • Orlando Anaya
        May 25, 2011 at 1:24 am

        Thanks a million! I just checked out netbeans IDE. SWEEET! I like it. anyway…. I do have a small issue. I modified your app to include a simple flashplayer off of my site and for the first time I am getting the redirection issues others are talking about. Any ideas on what could be wrong in my settings? I saw another post you had regarding this but I am assuming it is outdated as the solutions presented did not work. Thanks, Orlando

        • Orlando Anaya
          May 25, 2011 at 1:37 am

          once again… my bad. I didn’t have the proper url in



          after fixing this… app works fine again. Thanks!

  • zohaib
    May 25, 2011 at 12:39 am

    I used your tutorial v2 it worked fine. Now that I loaded new SDK v3. I have redirection issue. After users allow permission, it keeps redirecting back & forward. never takes me to the main page.

  • Ghost
    May 25, 2011 at 10:49 am

    thanks for the great tutorial. i tried your invitation dialog box, and made it into a single app. when i tried removing the authentication permission, the skip button on the invite your friends dialog box redirects to a ‘page request not found’ [url:

    what i’m basically trying to do is making an app that just allows user to invite their friends to my facebook page, and then when they press skip, they go back to my page as well.. any help would be appreciated.. thanks!

  • gecko
    May 25, 2011 at 1:35 pm

    thanks, I looking for facebook extended permission with php

    the example really usefull

  • Laurent
    May 25, 2011 at 1:52 pm

    Hi ,

    I have some problem testing your codes. my application keeps refreshing. and i notice the problem is this code :-

    if (isset($_GET[‘code’])){
    header(“Location: ” . $fbconfig[‘appBaseUrl’]);

    i don’t think facebook return me anything in the parameter.
    any advice?


    • mahmud ahsan
      mahmud ahsan
      May 25, 2011 at 1:56 pm

      Laurent by removing that isset() part code and updating below part check what happens

      $loginUrl   = $facebook->getLoginUrl(
                      'scope'         => 'email,offline_access, publish_stream, user_birthday,user_location, user_work_history, user_about_me, user_hometown',
                      'redirect_uri'  => $fbconfig['appBaseUrl']
      • Laurent
        May 25, 2011 at 2:36 pm


        The problem is still the same by doing as advice.


        • Laurent
          May 25, 2011 at 6:41 pm


          Looks like $_GET does work to get the ‘code’ from the URL. as i can see the variable there. and also no idea why the

          $user = $facebook->getUser();

          doesn’t work too. for me only .. i checked my settings and they look good


          • mahmud ahsan
            mahmud ahsan
            May 25, 2011 at 8:12 pm

            Did you update the latest PHP SDK 3.0 ?

          • Laurent
            May 26, 2011 at 7:24 am

            sorry for my mistake

            Looks like $_GET does not work to get the ‘code’ from the URL

            yes, i have updated to php 3.0. let me swipe everything clean. and re-try again. as it seems some of the folks here manage to get it working

          • Auz
            December 29, 2011 at 2:43 am


            Were you able to get this working? I am still having issues with refresh…

  • Imran
    May 25, 2011 at 5:58 pm

    Hello Mahmud,
    Thank you for nice posts, really like them.
    I have developmed on Iframe based app, and want to know if it is possible to add specific querystring everytime someone adds that app to page.
    for e.g. i have application url as follows

    If two users are adding this app to their fan page want to add some kind of id in querystring, so that i know which fan page it is loading in.


    • mahmud ahsan
      mahmud ahsan
      May 25, 2011 at 8:13 pm

      Sorry, I don’t know it :S

    • mhncsa
      December 8, 2011 at 3:17 pm


      (i know this is an old question, but maybe still need answer)

      there is a specific parameter called app_data.
      for example ?app_data=111111.
      but you can use only this one.

      so i use it like this:

      which means the current page is gallery and the current item id is 123

  • TGuarin
    May 25, 2011 at 11:12 pm

    Hi, i update to fb sdk3.0, the app working ok, but when i uninstall the app its not working.

    The line
    echo “top.location.href = ‘$loginUrl’;”; not working.

  • Ran Bar-Zik
    May 26, 2011 at 1:25 am

    Hi Mahmud,

    Thank you for great article and example. Thank you so much for sharing the information. I’ve tested your sample app and it works as I expected.

    • mahmud ahsan
      mahmud ahsan
      May 26, 2011 at 1:47 am

      Thanks for reading my post.

  • Daniel Enrique
    May 26, 2011 at 4:34 am

    Hi Ahsan,

    I changed to version 3 of PHP SDK, and works well in all browsers except IE, it redirects endlessly. Certainly the example of a page in IE also has problems. Any idea how to fix?


    • mahmud ahsan
      mahmud ahsan
      May 26, 2011 at 12:09 pm

      IE have some cookie issue, so write this code at the top of every page if your pages are different, or if you use the template system, then put this code at the top of that file. Hope if will fix your problem.

      • Daniel Enrique
        May 30, 2011 at 2:18 am

        Hi, thanks to your help I could solve the problem.

        Now I have a question. In your code example shows how to publish on the wall calling a popup (publishStream function) and it works fine, but I wish I could do the same for publication in the wall of a friend of my choice using the “UID”.

        I searched for several days and nothing works for me. I know how to do it without the popup, but I fear I disable Facebook application (already done on other occasions).

        I hope you can help me with an idea or a link.

      • Ramón Ramos
        November 12, 2011 at 5:50 am

        Dude thanks for the above header p3p code… you just saved my life (and by life I mean a really crappy day, but sounds way more cool that way).

        Anyway, if you want to rant about IE, our spirits will be together anytime.

        • mahmud ahsan
          mahmud ahsan
          November 17, 2011 at 2:39 pm

          Glad to know it helps. IE sucks!

  • Marco
    May 26, 2011 at 9:58 pm

    I wont create a simple tab application php for obtain name and surname of person liked my fan page,
    i have problem to get user information, can help me? thanks

  • Fred van der Ende
    May 27, 2011 at 4:05 am

    Hi Mahmud

    I love your tutorials, they have helped me a lot so far…

    Something I would like to implement is a button on our website from which FB connected users can invite their friends to check out our company Facebook page. With your tutorials I am able to build such a button. However, we want to offer an incentive to the users who really ‘do’ invite their friends, so we need to track who has been using the button!

    Any idea how to accomplish this?

    • mahmud ahsan
      mahmud ahsan
      May 27, 2011 at 11:31 am

      Yeah you can track then to whom they invite and you can additionally track who comes from invitation. You’ve to build your own database table for this. And follow what I said about invitation tracking in the post.

  • Álmos
    May 27, 2011 at 6:49 pm

    Hi there!

    This is a very very useful tutorial, so first of all thanks for it!

    Enligh is not my mother language, and my problem’s a bit complicated, but I hope you’ll understand it.

    There’s an applicaion on fb called Static Iframe Tab ( that which you can make a static html page with and put it on your page as a tab.

    I’d like to do something like this.

    The first time i opened this app, a dialog came up asking if I wanted to put it on my page as a tab. How can I call this dialog? I couldn’t find any information about it.

  • Álmos
    May 27, 2011 at 8:52 pm

    Hi there again!

    I realized, that add.php is doing what i need. Is that right? I just want to know how could i get the id of the facebook page where the user added my app as a tab.

    Does add.php send it back in a post parameter? Or how?

  • Orlando Anaya
    May 28, 2011 at 2:00 am

    For those of you still having problems with the eternal refresh issue with this app add this

    header('P3P: CP="CAO PSA OUR"'); ob_start(); 

    to the top of your index.php so first three lines should look like this.

    header('P3P: CP="CAO PSA OUR"'); ob_start(); session_start();
        include_once "fbmain.php";


    • mahmud ahsan
      mahmud ahsan
      May 28, 2011 at 10:11 am

      Thanks for your information.

      • Auz
        December 29, 2011 at 2:11 am

        Hi, your tutorial is a great asset, and I appreciate the time you have taken.

        However, I am also having the issue with constant refreshing afte user grants permissions. I have tried the header code given above, but it is still refreshing constantly.

        Here is the code I am using:

        Any idea? Thanks!

    • meltz
      February 20, 2012 at 6:54 pm

      thank you soooooooooo much, i been trying for days to get it working on IE that piece of crap.

      Really appreciated

  • Álmos
    May 28, 2011 at 9:07 pm

    I solved my problem. For those who have the same problem:

    You can get the id of the page your application is currently loaded in like this:

    $signed_request = $_REQUEST[“signed_request”];
    list($encoded_sig, $payload) = explode(‘.’, $signed_request, 2);
    $data = json_decode(base64_decode(strtr($payload, ‘-_’, ‘+/’)), true);
    $page_data = $data[‘page’];
    echo $page_data[‘id’];

  • dg
    May 29, 2011 at 1:51 am

    Very nice work!

    Just one thing…after user allows app permission, I keep getting a blank page after redirect. Can you help?

    • dg
      May 30, 2011 at 1:02 am

      oops my bad…fixed it…didnt have correct url set in fbconfig…

      great work!

  • Dale Ross
    May 30, 2011 at 8:42 am

    Hi Mahmud,

    I am experiencing the eternal refresh issue in IE.

    I have tried



    header(‘P3P: CP=”CAO PSA OUR”‘); ob_start();

    but neither appears to work.

  • Euler
    May 30, 2011 at 12:23 pm

    Hello Mahmud,

    where is cancel_url variable, in the new sdk 3.0? What is the replacement?

    • mahmud ahsan
      mahmud ahsan
      May 30, 2011 at 8:04 pm

      I don’t see any cancel_url type parameter in the sdk 3.0 library.

  • Tim Hussey
    May 31, 2011 at 8:32 am

    I can’t thank you enough for your sample code!!!!
    You’re AMAZING!!!

    I wanted to know if you knew how to do the following
    (because I desperately need to know how to do it)

    I’ve seen apps like this one (
    that give the user who adds it the option to save different parameters…

    Can you either #1 help me figure that out, like prompt the user to enter in a custom API key and passphrase (from my web app)

    and then save that so that way on their page’s tab, it can show the right form depending on their parameters entered…?

    I can send you an example app that does EVERYTHING I want mine to do…

    If you don’t want to write and article but are willing to help me, I can pay you some $$$ (not a whole lot, due to not having a big budget for my simple app)

    Let me know 🙂

    Your ROCK!

    • Tim Hussey
      May 31, 2011 at 10:33 pm

      just let me know when you get a chance Mahmud!!
      You ROCK! 🙂

      • mahmud ahsan
        mahmud ahsan
        June 1, 2011 at 12:11 am

        Hello, Unfortunately I’m highly busy, working on iOS projects, working on my clients web project and additionally learning guitar. So I couldn’t help you in this point. :S

  • lucie
    May 31, 2011 at 8:44 am

    Hi mahmud,

    first i will tell to you thanks for your help and great website.

    All is working perfectly after i follow your tutorial !

    Now i try to have the “auto publish stream” on the wall of the user like i have actualy with my old rest API

    (when a user allow the application a “wallpost” is displayed in his own wall its automatic)

    I have this with my old rest api just after the old

    $user_id = $facebook->require_login($required_permissions = ‘publish_stream’);”

    old api here :

    $message = ‘my message here’;
    $attachment = array( ‘name’ => ‘attachement here’, ‘href’ => ‘’,
    $action_links = array( array(‘text’ => ‘message’, ‘href’ => ‘‘)); $attachment = json_encode($attachment); $action_links = json_encode($action_links);
    $facebook->api_client->stream_publish($message, $attachment, $action_links);

    but i try now SDK3…dont find how to do “auto publish stream when you accept the app

    I hope there is a way to do it ! Thanks you !

  • fm
    May 31, 2011 at 2:12 pm

    hi mahmud, can teach me how to save the user data after being granted permission?

  • lior
    June 1, 2011 at 2:01 am

    Hello Mahmud,
    can you tell me please how to loop the request id array after invite and save the user id in the database?

    thank you

    • rui
      June 28, 2011 at 6:54 pm

      Did you solve this?

    • rob12345
      October 17, 2011 at 10:09 pm

      Did you solve?

  • Huh
    June 1, 2011 at 11:50 pm

    Stream publishing doesn’t work. Even in your app…

  • shay
    June 2, 2011 at 2:33 am

    how does “offline_access” works? I am successful at granting permission for offline access. do u have a tutorial on this. do u recommend any other site tutorial.

    I found this (

    but I thinks is Old api and SDK 2.

  • istop
    June 2, 2011 at 1:42 pm

    why can’t i print the user’s basic info? does anyone having the same problem? thanks

    • mahmud ahsan
      mahmud ahsan
      June 3, 2011 at 1:57 am I’m seeing the basic information of user under User’s Basic Info. Have you checked that ?

      • istop
        June 3, 2011 at 10:49 am


        on your demo, i can see my user basic info.

        i downloaded your code, input my appid, secret, baseurl, appbaseurl. when i load the page, authentication runs ok. it displays my ID and session array but the basic info array is blank. am i missing something here? thanks

  • steve
    June 3, 2011 at 5:44 am

    mahmud ahsan,

    Thanks for the update for 3.0x works like a charm with the basics..

    I’m trying to expand your system with useing jquery tabs and ajax to load in another php or html page into the tab.

    I just use the jquery ajax tab system, which is quite easy.. you just create a li for your menu with the url for example..


    and then on the home.php page put the empty div tag

    so that works.. but on my test.php page, I cannot get any fb data anymore.. $user doesnt seem to work, it gives me an undefined variable…

    this is my test.php page

    } catch (FacebookApiException $e) {
    //you should use error_log($e); instead of printing the info on browser
    d($e); // d is a debug function defined at the end of this file
    $user = null;

    if i add include_once “fbmain.php”; on the test page, it just refreshes the page and loads the main tab or Home page.

    any thoughts on this? seemed to work fine with php 2.x sdk

    • mahmud ahsan
      mahmud ahsan
      June 3, 2011 at 2:14 pm

      I don’t know what is the problem, my demo and code is working nicely.

      • steve
        June 3, 2011 at 11:58 pm

        try the above, the issue is loading a html or php page into a tab instead of having all the html code and links in home.php

    • Morphine
      April 6, 2012 at 5:39 pm

      Hi, I also get a undefined error.. curl is enabled on our server.. please help

  • istop
    June 3, 2011 at 12:16 pm


    seems to be not working. am i missing something? thanks

    • mahmud ahsan
      mahmud ahsan
      June 3, 2011 at 2:13 pm

      its working for us and also in our code and demo.

  • istop
    June 3, 2011 at 10:10 pm

    it turned out that the use of CURL function in the hosting site was disabled. i had it enabled and everything is working just fine now. thanks mahmud.

  • suhel khan
    June 6, 2011 at 4:06 pm

    The above demo apllication is not working Properly in IE8, Stream Publish Box Is not Working Properly At all

  • Jason
    June 7, 2011 at 7:56 am


    I like your demo but I had a question, I didnt want to clutter my home.php page with all the code I need to write. I prefer to have tabs that load up various other php pages.. like invite.php , game.php and each one of those loaded in the jquery widget.. but im having a hard time figuring out where to start with this part.. any advice or thoughts on how to just load a simple php page in as a tab ?

    • mahmud ahsan
      mahmud ahsan
      June 7, 2011 at 12:01 pm

      yeah you can do it easily, just include fbmain.php in all your pages, and if you use javascript sdk then include javascript library code in your template page where you’ll load different page.

  • Brian
    June 8, 2011 at 2:44 pm


    I love this code and facebook needs to follow suit and provide better documentation. My question is this, I used your code and plugged in my own specifics and the app works fine and exactly like your demo works except for anything to do with publishing, when I try to send request/invitation, stream publish, or status update I get an error every time. with send request and click here I get an error from facebook, and then when I click ok on the error the title bar says XD Proxy and the address bar starts with server generated code after that

    any idea why this is happening. Do I need to install the javascript sdk too or anything for ajax or jquery. I am using wamp with apache, php, and mysql and curl extensions are enabled. As I said the app works fine, authorizes, and displays correctly and that the only problems I am having have to do with the fnctions basically. all the code is working except for the publish, streampublish and newInvite functions in the index.php file. I am stumped and any help you can provide will be eternally appreciated. Thank you in advance

    • mahmud ahsan
      mahmud ahsan
      June 8, 2011 at 4:11 pm

      Use javascript sdk and check what happens.

      • Brian
        June 8, 2011 at 4:20 pm

        May be a dumb question, but you use javascript sdk the same as php correct? I mean, do I put the contents of the zip folder from github in my app directory on the server and include all.js.php?

      • Brian
        June 8, 2011 at 8:26 pm

        I think I know what the problem is, since I am only having errors with any of the feeds it makes sense that it is because this sample code doesnt reflect the access token change that went into effect June 3rd. From what I am understanding from the documentation every single post is going to require the use of access token. See if what I am saying makes sense to you or if I am off on a tangent that wont help me lol

        This is where I got the info

  • mads
    June 21, 2011 at 5:46 am

    Hey Mahmud,

    Great work on this API, loving it, but i have some questions. For instance, when i use facebook connect on other pages, the page remembers my login, but your script doesnt seem to, is this intentionally or is this an error?

    • mahmud ahsan
      mahmud ahsan
      June 23, 2011 at 12:09 am

      When facebook will update their javascript SDK I think then this problem will solve.

  • Yossi
    June 21, 2011 at 11:10 pm

    I try to add to index.html code
    of reading events from user($user) and when I run the app event I got err
    “Fatal error: Call to a member function events_get() on a non-object in /home5/centerwo/public_html/facebook/template.php on line 142”

    my code:
    $events = $facebook->api_client->events_get($user, null, $start_time, $end_time);
    what I miss here ?

    • Yossi
      June 22, 2011 at 12:18 pm

      Hello Mahmud,
      can you add code of creating and reading event please

      thank you

  • Andrew P.
    June 23, 2011 at 1:20 am

    Hi Mahmud!

    Great tutorial!!

    I have one question. I use your tutorial but when an user clicks on “Don’t Allow” it keeps redirecting to the permissions page, how can I redirect to home page when that happens?

    Thank you so much

    • Andrew P.
      June 23, 2011 at 1:35 am

      Just adding to the loginUrl “‘redirect_uri’ => ‘myapp'” it works. Thanks and keep up the great work

  • Shaon
    June 23, 2011 at 11:53 am

    Thanx a lot mahmood vai for your excellent tutorial. It helps me a lot for building the FB application. One query, is it possible to send email using facebook application??
    I can collect the email address, but is it possible without collecting??

    • mahmud ahsan
      mahmud ahsan
      June 23, 2011 at 5:46 pm

      No, it was possible during 2008-2009, but now that is not possible. You’ve to use your own mailing system to send mail. If you use php you can use mail() function for that.

  • Sulman Ahmed Malik
    June 24, 2011 at 4:17 am

    i am using your graph api i want to know how to get user mobile number using graph api. 2nd thing i change code to work in code igniter i faced one problem the graph api is working at localhost but donot work on my testing server.

    after login i run the following code in register view but register view donot work properly please guide me i am very tahnkfull to you

    here is the following code

    $fbconfig['appid'] = "appid here";
    $fbconfig['api'] = "api key";
    $fbconfig['secret'] = "secrete";

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


    // 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();

    $fbme = null;
    // Session based graph API call.
    if ($session) {
    try {
    $uid = $facebook->getUser();
    $fbme = $facebook->api(‘/me’);
    } catch (FacebookApiException $e) {
    // d($e);
    try {
    //get user id
    $uid = $facebook->getUser();
    //or you can use $uid = $fbme[‘id’];
    } catch (Exception $o) {

    // function d($d){
    // echo ”;
    // print_r($d);
    // echo ”;
    // }

    $fbId = ”;
    $fName = ”;
    $lName = ”;
    $email = ”;
    $birthdate = ”;
    $location = ”;
    $gender = ”;
    $picture = ”;

    $fbObj = $this->users_model->getUserInfoByFbId($fbme[‘id’]);
    if (isset ($fbObj->id)) {
    if ($fbObj->status == 1) {
    $this->session->set_userdata(‘user_id’, $fbObj->id);
    $this->session->set_userdata(‘login_id’, $fbObj->email);
    $this->session->set_userdata(‘fname’, $fbObj->first_name);
    $this->session->set_userdata(‘lname’, $fbObj->last_name);
    $this->session->set_userdata(‘birthdate’, $fbObj->birthday);
    $this->session->set_userdata(‘location’, $fbObj->location);
    $this->session->set_userdata(‘gender’, $fbObj->gender);
    $this->session->set_userdata(‘picture’, $fbObj->imgpath);
    $this->session->set_userdata(‘fb_uid’, $fbObj->fb_uid);

    redirect(‘users/getloginuser’, ‘refresh’);
    } else {
    $fbId = $fbme[‘id’];
    $fName = $fbme[‘first_name’];
    $lName = $fbme[‘last_name’];
    $email = $fbme[’email’];
    $birthdate = $fbme[‘birthday’];
    //$location = ;
    $location = $fbme[‘location’][‘name’];
    } else {
    $location = ‘Null’;
    $gender = $fbme[‘gender’];
    $fql = “select pic_square from user where uid=”.$fbId;
    $param = array (
    ‘method’ => ‘fql.query’,
    ‘query’ => $fql,
    ‘callback’ => ”
    $fqlResult = $facebook->api($param);
    $picture = $fqlResult[0][‘pic_square’];

    $this->session->set_userdata(‘fb_uid’, $fbId);
    $this->session->set_userdata(‘fName’, $fName);
    $this->session->set_userdata(‘lName’, $lName);
    $this->session->set_userdata(’email’, $email);
    $this->session->set_userdata(‘birthdate’, $birthdate);
    $this->session->set_userdata(‘location’, $location);
    $this->session->set_userdata(‘picture’, $picture);
    $this->session->set_userdata(‘gender’, $gender);

    redirect(‘users/fbsave’, ‘refresh’);
    // $fbObj = $this->users_model->getUserInfoByFbId($fbId);

  • Athanasios
    June 24, 2011 at 5:48 pm

    How can I deny direct access to the application sitting on the server ( I want my application to be accessible only through facebook and without the use of Javascript redirect.

  • Alex Mustin
    June 24, 2011 at 9:54 pm

    Thanks Mahmud for the tutorial! Great info that can all be found in one place – very helpful.

    Unfortunately I seem to be experiencing some issues in IE7:

    – the “publishStream” function doesn’t execute when used in “onClick” on an anchor link… same with “newInvite” function

    – jQuery form validation doesn’t work

    These issues are only happening on IE7, but it works great in all new browsers (including IE8).

    Does this mean the jQuery is having issues with IE7? I’m stuck. Can anyone help me understand what the issues are?

    • mahmud ahsan
      mahmud ahsan
      June 27, 2011 at 2:00 pm

      IE sucks, I am sorry as I do not know what is the reason for IE7.

      • Alex Mustin
        June 27, 2011 at 10:06 pm

        While I completely agree with you, we can’t ignore the reality that people are still using old browsers.

        I found a solution:

        Use Custom Channel URL

        1.Add channelUrl parameter in FB.init session.

        appId : ‘YOUR APP ID’,
        status : true,
        cookie : true,
        xfbml : true,
        channelUrl: “http://yourdomainname/fbtest/channel.html” //Add this file in your website.

        2.The contents of the channel.html file should be this single line:

        3.Test your FB login…Enjoy…

        Reference URL:

        • Alex Mustin
          June 27, 2011 at 10:13 pm

          sorry, the line for “custom.html” should be:

          (script src=””)(/script)

          replace () with

  • Yasser
    June 26, 2011 at 3:41 am

    hi Mahmud,

    First of all thanks for the tutorials.

    Im working on real-time update.
    I get this Error:
    OAuthException: Invalid OAuth access token signature.

    This is how i get my access-Token:

    $my_access_token = file_get_contents(‘’.$facebook->getAppId().’

    Is this the wrong access-token ?

  • Yasser
    June 26, 2011 at 4:59 am

    hi again..

    i solve the problem . i forgot to add this :
    $access_token = str_replace(‘access_token=’, ”, $my_access_token);

    But now i get this Error:
    OAuthException: (#2200) callback verification failed: connect() timed out.

    It seems that the FB-Server can’t connect to my server.
    Is it because im working on localhost and using DynDNS ?


  • Prince Merluza
    June 26, 2011 at 6:23 pm

    I have a question. Why do you have to make $userInfo, can’t we just use $user_profile instead?

    • Kashif
      June 28, 2011 at 12:27 pm

      @ mahmud ahsan

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

  • Abdul Baquee
    June 28, 2011 at 6:14 pm

    I read your post it’s an awesome dude ! I always come back visit your blog time to time.

    Thanks !

  • rui
    June 28, 2011 at 7:41 pm

    Hello and thank you for helping me thinking diff 🙂

    I have some questions about the invite stuff and the tracking this is my scenario:

    I have several function newInvite (newInvite2, etc..) inside my aplication each one have a custom message and the user can invite their friends and everything is working fine.

    Now is it possible to show that user what invites he send to what friends? and witch ones were acepted?

    and wend a invited user lands my app how can he see what were the invites that his friends send him?

    I can’t seam to wrap my head around the developers.facebook docs.

    • rui
      July 6, 2011 at 9:26 pm

      Ok now i’m able to retrieve all app requests for a visiting user

      $request_url =”” .
      $user_id .
      “/apprequests?” .
      $requests = file_get_contents($request_url);
      echo ”;
      echo ”;

      But how can I show to the user who and how manny invites were accepted by his friends?

  • Pino
    June 29, 2011 at 11:42 pm

    Hi, Mahmud you’re our hero! 🙂

    I have a question regarding the form submission. In SDK 2.x when submitting a form to my URL I got the $user_id with
    $user_id = $facebook->getUser();
    but now it returns 0. I don’t like the idea of passing the user_id as a form parameter. Any suggestions?

  • rjoseph
    June 30, 2011 at 4:55 pm


    I want to get information about the Invite button for a page. Now the FB.ui(method:’apprequests’) sends the application request. while the user click on it, it shows a page to install the same.

    If I want to invite to a page of mine, hows it can be possible from iframe

  • Yaary
    July 4, 2011 at 5:55 pm

    Hi; thank you for a greate post.

    I downloaded and installed your sample. each time the application is loaded i am redirected to my website and the not the iframe page.

    next time application is accessed that sample is loaded correctly.

    not only is there a redirection but with a paramater names code and its value, like this:

    is this supposed to happen?

    • Yaary
      July 5, 2011 at 2:57 pm


  • Saurabh Chokhra
    July 6, 2011 at 9:07 pm

    Mahmood Thanx a lot .really a great tutorial.
    But I am please tell me where should i upload the code?
    where should i host my code as facebook is not hosting the code?
    i want to make an app for fun so where i can host cheaply?please suggest me .
    A big big thanx in advance 🙂

  • haries
    July 7, 2011 at 11:03 am

    Mahmood Thanx a lot .really a great tutorial.
    I have downloaded your code, but after I uploaded and I have adjusted as the Application ID, API Key, App secret and other parameters, when I run my application, my application continually redirect to that page.
    When I checked, the script in my application:

    $ session = $ facebook-> getSession ();

    not running and not generating value.
    my url application :
    Can you help me.

    • Pino
      July 7, 2011 at 2:42 pm

      You may have downloaded the old version. In the new one there is no $facebook->getSession() but instead $user = $facebook->getUser();

      Go through the tutorial again and check you have everything in place.

  • chiku
    July 10, 2011 at 2:24 am

    tutorial is great ..

    but the problem with my app is that ,when i played it for the first time it doesnot post to my wall THAT I HAVE STARTED USING THING THE APPLICATION…it post when i play the app more than 2 times ..

    and i have not submitted my app in app directory ..
    so how can i recitfy that problem …

  • Mobile News
    July 13, 2011 at 8:08 am

    Thanks for this help….

  • andy
    July 19, 2011 at 12:35 am

    Hi its possible redirect to some url after invite friends?
    exactly when you push “send reguests” thanx a lot!

  • Thary
    July 22, 2011 at 1:20 pm

    your website is fantastic. But I still have some problems when I try to load another page after I pass an album id while I want to get the photo in that album. It seems like I haven’t authorized the app but actually I did because in my index page I can get user album data.

    I have tried to offline_access extended permission but it’s useless. and I also tried add your fbmain.php into my page but it reloaded again and again and after that it redirects to index.php

    Any idea about this?

    And I wonder whether FB app support local session?

    Thanks in advance

  • nizar
    July 22, 2011 at 4:19 pm

    Hi, A good tutorial but I need your help
    I am new in Facebook Apps development but a bit skilled in PHP-based web application.
    I am deveopping a PHP Mysql voting system that allows users to choose from options. I have developped this app and made it as Facebook App.

    Here I need help to improve it to fit my needs.
    My First question is :

    Is it possible to use the FB connected condition to make the fisrt page of the app visible only to fans of the page in

    which I am using the app ?

    My second question :
    Is it possible to store some of the User’s Basic Info into my database ( id, email, hometown … ) because they will be

    needed to classify the voting results ans to send them to people who have voted by their email.

    Thanks in advance

  • mahmud ahsan
    mahmud ahsan
    July 22, 2011 at 5:17 pm

    Yeah both are possible.

    for first question, when user login via facebook in your site, just grab user’s ID and using FQL query check if user is fan of your page or not. And based on the result show him what you wanted.

    And for second question, you can follow my this article (this is based on facebook Sdk 2.0)

    • nizar
      July 22, 2011 at 8:31 pm

      Thanks a lot for your answer it is very helpful. Please can I discuss with you directly through Skype or msn or FB. This is my Skype nizar.b78
      msn : khomsa.arts @ and the same address for FB

  • Vinay
    July 24, 2011 at 1:35 am

    Hello mahmud,

    I am facing a problem.

    when i use this
    it return the information of all the albums. and album id as “257536820926628”
    but when i use “id” return from above to show cover photo in this passion“.$ret[$i][‘cover_photo’].”?access_token={$access_token}

    it return some strange number instead of id like 2.57536930927E+14

    firebug says that for above id it gives … XXXXXXXXXX

    also sometimes hardly 10% it works fine
    I am wondering what is this problem. is this problem problem due to max integer length ? or anything else ?

    Let me know if you ever face this problem or have solution to this problem

    thanks in advance

  • LostDeveloper
    August 3, 2011 at 5:21 am

    I am having trouble setting facebook sdk on my website. Can someone pleeeease help a fellow developer? I am new, but would like to learn this to create more social sites using FB api as well as Googles & Twitter. Please guide me as I can not understand all of this. I just started learning javascript and mild knowledge of php. I used to use FBML with ease but now need API functions to make sites more fun & interactive. I have a couple dollars but very poor. Thanks for anyone who offers assistance!

  • LostDeveloper
    August 3, 2011 at 5:22 am

    oh, my email:

  • Rhenan
    August 11, 2011 at 8:30 pm

    Well, I am developing an application for facebook but wanted a way to after the User clicks “like” the fanpage display another page within itself, because I saw a few tutorials here but are no longer working. Thanks if you help me, really like your tutorials …

  • ahmed
    August 13, 2011 at 7:42 pm

    hi mahmud

    if i used this tutorial like is this my app work normally or what cuz i don’t know php and java just little from php all i need the script and i put my data from app id and secret key from my app and after that my app work normally and my front page from my app is radio.php (how i make the user after click like my front page display within itself )

    • mahmud ahsan
      mahmud ahsan
      August 13, 2011 at 11:46 pm

      Sorry I’m not clear what information actually you wanted.

      • ahmed
        August 14, 2011 at 4:44 am

        please visite my app ( you will see your app not my app from where i can add my front page in my app (my front page called radio.php)

        • mahmud ahsan
          mahmud ahsan
          August 14, 2011 at 4:26 pm

          After redirect your link is not working.

          • ahmed
            August 15, 2011 at 6:18 am

            from where i can add my redirect link ??? which file you you mean to edit it to be sure only

  • Rhenan
    August 14, 2011 at 4:03 am

    Well, I am developing an application for facebook but wanted a way to after the User clicks “like” the fanpage display another page within itself, because I saw a few tutorials here but are no longer working. Thanks if you help me, really like your tutorials …

  • Cris
    August 18, 2011 at 11:17 pm

    i have a website and i place likes on a couple of subpages. If i go to the Insights page Like button -> Popular Pages i can see the pages that have been liked.

    My question is how do i get those pages (url’s) and the information that comes with it.

    I could use links.getStats to get the info i need but i need to pass a list of url’s and i don’t know how to get it

    Any ideas?

  • Usman
    August 21, 2011 at 9:49 am

    When I allow the App to Access my Info then it keep on refreshing the page and the page never stops.Please anyone there to help me….

  • Tolu
    August 22, 2011 at 5:23 pm


    Nice tutorial. Please, how do I get users who receive invites from my app to land on the iframe app page on facebook when they click on the invite and not on the app profile page?

  • Pitso
    August 22, 2011 at 6:43 pm

    Hi! i was wondering how can get user id and store it in my database.
    Thanks for helping me get started with FB Apps.

  • usman
    August 22, 2011 at 11:33 pm

    Admin Can you please upload a code of above tutorial with latest tutorial present at
    I shall be very thankful to you.
    The latest tutorial has two files with it.

  • André
    August 23, 2011 at 1:38 am

    Hello mahmud,
    Congratulations for the tutorial!

    I created the application using your tutorial and it worked perfectly, but how do I post on the wall of the user when he is not logged. I have already entered the stream offline, but I could not write the data to mysql database using:

    if (isset ($ _GET [‘request_ids’])){
    / / Comes from user invitation
    / / track if You Need Them


    And even if he could, as you would use it to publish? Thank you for your help.

    • ahmed
      August 25, 2011 at 3:20 am

      from where i can add my redirect link ??? which file i cab edit it to redirect to my app page

  • Ajay516
    August 25, 2011 at 1:10 pm

    after login success can’t get details of user plz help me

  • Shwetha
    August 26, 2011 at 1:33 pm

    Hi, Here i will post my code please let me know what is the error in this, since i am not able to login to fb.


    $fbconfig[‘appid’ ],
    ‘secret’ => $fbconfig[‘secret’],
    ‘cookie’ => true

    $me = null;

    if ($session)
    $me = $facebook->api(‘/me’);
    catch(FacebookApiException $e)
    echo $e->getMessage();
    if ($me)
    $logoutUrl = $facebook->getLogoutUrl();
    echo “Logout“;
    $loginUrl = $facebook->getLoginUrl();
    echo “Login“;

    Output :

    An error occured in the script being debugged:

    session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\Shwetha\testf\testf.php:7)in C:\xampp\htdocs\Mithun\testf\facebook.php on line 37 PHP Stack trace: PHP

    1. {main}() C:\xampp\htdocs\Shwetha\testf\testf.php:0 PHP 2. Facebook->__construct($config = *uninitialized*) C:\xampp\htdocs\Shwetha\testf\testf.php:19 PHP 3. session_start() C:\xampp\htdocs\Shwetha\testf\facebook.php:37 PHP Notice: Undefined index: appId in C:\xampp\htdocs\Shwetha\testf\base_facebook.php on line 213 PHP Stack trace: PHP 1. {main}() C:\xampp\htdocs\Shwetha\testf\testf.php:0 PHP

    2. Facebook->__construct($config = *uninitialized*) C:\xampp\htdocs\Shwetha\testf\testf.php:19 PHP

    3. BaseFacebook->__construct($config = *uninitialized*) C:\xampp\htdocs\Shwetha\testf\facebook.php:39

    • Shwetha
      August 26, 2011 at 1:39 pm

      Sorry here few starting lines are missing please find those here:

      etc tags..
      $fbconfig['appid' ] = "100…….";
      $fbconfig['secret'] = "bed…….";

      include 'facebook.php';

      $facebook = new Facebook(array(

    • mahmud ahsan
      mahmud ahsan
      August 26, 2011 at 4:10 pm

      put session_start(); function at the top of the main file.

  • Shwetha
    August 28, 2011 at 4:28 pm

    Hi Ahsan,

    Now i am able to get the feeds from users Fb page, but when it appears in my page it looks messy, i wanna make it in a structured manner,.

    How can i make it..? i wanna page to appear based on the tags for
    eg., [name] ahsan
    [id] 123456789
    so on..

    thanks in advance

  • Semih
    August 29, 2011 at 4:37 am

    Just one thing: You are great… God bless you

  • Raul
    September 1, 2011 at 8:54 am

    Hi Ahsan, how can i get the friend_photos? which table or query I have to do?

    You are great… Thank you

  • Servando
    September 1, 2011 at 10:41 am

    Hello Ashan you article is very helpfull and clear.

    I need your help with this, if you can plzz here is the question:

    If the user authenticate in our app and he has a personal profile page and pages that he is admin of.

    Can we allow user to post on his personal profile page and the pages that he is admin of??

  • Mark Bell
    September 1, 2011 at 11:47 pm

    Hello, first of all thanks, this is a very comprehensive bit of code. I have a slight issure though that is driving me crazy. When I use the PHP header() function, I get a headers already sent error. I have stripped all of the cosmetics out of the body tag and just literally have 2 blank pages, header1.php and header2.php. I have header(“Location: header2.php”); within header1.php and I still get the error. Is there something I’m overlooking? Many thanks, Mk

  • P
    September 5, 2011 at 6:25 am

    I was trying to download the files but I got Status 404 Not Found. 🙁

  • Shwetha
    September 7, 2011 at 1:59 pm

    HI Ahsan,

    I was trying to get htc feed info, i just wanna get only “message” tab data how can i get it..?

    i tried the following code but it didnt work

    $htcPage = $facebook->api(“/101063233083/feed”);
    print_r ($htcPage[‘message’]);


    echo $htcPage[‘message’];

    both didnt work. Please help me.

  • sri
    September 10, 2011 at 5:29 pm

    i have used your code, I changed the app ID, secret, Base URL and Canvas URL, everything is fine except the app doesn’t ask for user authorization.

    i have changed nothing else in code, i don’t know why i am facing this problem.

  • Darryl
    September 16, 2011 at 12:46 am

    Hey Ahsan,

    I used your original tutorial to get an app up and working on facebook about a year ago. Then it stopped working with the Facebook change to SDK 3.0 and I haven’t been able to get it working since the change. I had no problems with the original tutorial, but here the call to create a new facebook object where you include the appID and secret never returns an object with the userID, even when logged in to Facebook. So obviously everything else fails. Does anyone have any ideas? I’ve been running into this for over a month now with no success.


  • @nd3r
    September 16, 2011 at 2:55 am

    Hi Mahmud,

    If a user allows my fb connect in which i asked permission to get “others people info” (for example friends_birthday,friends_group) how can I see this information. I can only see the person signing in info.

    Thank you and congratulations for this wonderful blog!


    • mahmud ahsan
      mahmud ahsan
      September 19, 2011 at 1:27 am

      You’ve to pass the permissions to get this info during login url, and using FQL or other graph api call you could grab the info.

  • HighFlyer
    September 18, 2011 at 9:36 am

    Hi, check your tutorial and it seemed to work.
    Thnx for that! It is the first tutorial that did work.

    But i have one question that remains:

    What should i do if a user does not allow my app?

    • mahmud ahsan
      mahmud ahsan
      September 19, 2011 at 1:26 am

      You’ve to do nothing.

  • nufat
    September 18, 2011 at 11:17 am

    how to change title, in share facebook title no like my project

  • Wouter
    September 18, 2011 at 10:16 pm

    hey there,

    Mahmud, thanks for this tutorial!

    But I did have some problems getting it to work, got in an infinit loop (whie getUser always returned 0), but eventually found the solution:

    instaed of using the $fbconfig object that holds the appid and secret in this piece of code:

    $facebook = new Facebook(array(
    ‘appId’ => $fbconfig[‘appid’],
    ‘secret’ => $fbconfig[‘secret’],
    ‘cookie’ => true

    I insert them directly:

    $facebook = new Facebook(array(
    ‘appId’ => “1179423423478468305817”,
    ‘secret’ => “db16218e9fc24234234ea05c6e4f9acfa1cd81”,
    ‘cookie’ => true

    And then it worked!

    very strange, but maybe it helps some people here….

    Or maybe someone even knows why this works?


  • Ian
    September 20, 2011 at 1:32 pm


    Your tutorials have been a great help. My first app just required the user authorization/login stuff but now I’m working on a variation of a gift app.

    I’ve been looking at the php-sdk docs and other examples and I can’t seem to discover the current methods for passing variables from an HTML form to the app.

    e.g. A user writes a message in a textarea, chooses an item with form radio buttons, and then chooses the friend(s) to send it to.

    How are the text area and item choices sent along with the user id for the request? Trying to solve this piece of the puzzle is one of the biggest hurdles to moving forward with my app.

    Thanks for any advice.

    • mahmud ahsan
      mahmud ahsan
      September 20, 2011 at 4:54 pm

      In the demo there is a tab Status Update where is a text field is located. And here I am using ajax to pass data from front end to php backend. If you don’t want to use ajax then write php code to process the form. That’s easy. Mention the action parameter of the form tag and also you should use Method as “POST”

      • Ian
        September 20, 2011 at 10:40 pm

        Thanks, Mahmud.

        I guess where I’m getting stuck is in creating a page that combines an html form with a friend-selector.

        If I have:

        …my form choices

        Which type of friend-selector should I call after it? And does hitting “send request” on the friend selector create a POST action for the form?

        That’s my main stumbling point. I just haven’t found anything in FB’s docs that show me how to do this.

        I appreciate your insight!

        • Ian
          September 20, 2011 at 10:44 pm

          hmmm…don’t know how to get code to show up in your comments but “…my form choices” was wrapped in form action=”” tags. 🙂

  • Alex Brown
    September 20, 2011 at 10:27 pm

    First of all i would you like you thank you about this grate article. but i cant understand how “invite your friends” install in to fanpage.Can you please help me mahmud ahsan


  • SergiOasiS
    September 20, 2011 at 10:36 pm

    Hi! Thank you so much for this tutorial! Looks and works great! Congrats!

    I have a concern. On October 1 Facebook requires Secure Canvas URL (HTTPS).

    I´m a PHP Developer and I dont have experience with HTTPS. So, my doubt is:

    I have to change some PHP code for this to work? Or is a server side issue?

    I would greatly appreciate your help.

    Thanks! (And sorry for my bad english)

    Sergio from Argentina!

  • Kenedo
    September 26, 2011 at 3:59 pm

    Hi Mahmud, I’m just starting develop facebook application and learning through
    your tutorials. But I’m not quite understand about the invitation tracking
    which involved of the request ID & receiver ID.
    Currently I want to track the invitation that the user have sent,
    so that I can know that which how many invitation or requests….

    I found no way to do it, so can you please show me the codes?
    Very appreciated for your help!

  • Tass
    September 30, 2011 at 6:29 pm

    I tried your code , But when i click Send Request/Send Invitation , i got pop with error Like

    An error occurred. Please try again later.

    Can you help me on this

  • kalin
    October 3, 2011 at 1:39 am

    anyway you can set up a facebook session and a photo upload for me on my website and ill pay you. I cant seem to get it from the online help.

  • Johan
    October 6, 2011 at 8:34 pm

    Is Authentication required for invite friends and stream publish? If not, what lines do I have to delete to skip the authentication?

  • russ
    October 8, 2011 at 11:29 pm

    Great piece. I have followed along and everything is working fine. I have a question, will all of this work with the new signed request required on October 1st. I am new to this, so wondered if the code will still work ?
    Thanks in advance

  • rob12345
    October 17, 2011 at 10:08 pm

    Hello Mahmud,
    can you tell me please how to get via PHP the user id after the invite?

  • Moaaz
    October 21, 2011 at 10:52 am

    Hi Mahmud,

    Many thanks for you and for your tuts
    i have a problem here that i have make the proper permission code and runs perfectly
    but it always give a login dialog even i’m logged in , this dialog hasn’t username and password inputs , it’s just a dialog with login button

    after login it gives the permission dialoug ( regular ) expected to get this one directly without the previous one !

    and after allowing the permissions it redirects the user into the app source (on my website) not the app URL on FB .

    many thanks for your help

  • Linh
    November 14, 2011 at 9:56 am

    Hi mahmud ahsan
    Thanks for tour :

    i like feature : 6. How to request/invite your friends and track them

    User received invite , he is click to and allow finaly redirect to iframe ( inside app facebook) . I don’t like redirect to inside facebook , i like redirect outside , example : redirect to my site.

    Do you have solution for me?


    • mahmud ahsan
      mahmud ahsan
      November 17, 2011 at 2:36 pm

      In that case you can provide extra parameter to detect user’s click and then you can manually redirect your user to your site.

  • Peppos
    November 19, 2011 at 1:23 am

    Hello Mahmud,

    THank you for your great tuts! I’m trying to use your script but there’s a problem getting user id.

    I’ve added
    if (!$user) {
    exit(‘No user ID’);
    just after $user = $facebook->getUser();
    and the output is “No user ID”

    Could that be a problem with the application settings?


  • Kim Al
    November 23, 2011 at 12:36 pm

    Hi Mamud,

    This tutorial is very helpful… But I’ve got a problem with Google Chrome. Your demo link when opened with Google Chrome results an error:

    “This webpage is not available

    The webpage at might be temporarily down or it may have moved permanently to a new web address.

    Error 501 (net::ERR_INSECURE_RESPONSE): Unknown error.”

    This error also appears when I open my application. Do you have a solution for this?

  • David Randle
    November 25, 2011 at 8:13 pm

    Brilliant tutorial!! I just have a quick question…

    When trying to track invitations when a user accepts the invite, how do I grab the ID of the user the invitation was sent from?

  • Luiz Zamboni
    December 1, 2011 at 12:51 am

    Hi, I m tried use this like a framework, but i see any diferences in bahavior of your app in facebook and yout code. See: this is my app, it is just a exactly copy of your code this is your app

    In mu app, the auth leave 2 steps, unlike of others app that i see…

    How can be happend to this diferent bahavior inf Autentication ?

  • ken
    December 4, 2011 at 4:51 pm

    seems about me, activities, interests, music, movies.. is now gone from fb ???

    • ken
      December 4, 2011 at 4:59 pm

      cant seem to extract the info.. nor can i now find on fb where that info has gone.. disappeared into cyberspace ?

  • keshav
    December 8, 2011 at 2:54 pm

    absolutely fantastic!!!!!…. awsm tutorial

    i think i m ready for designing!!!

  • Raju
    December 13, 2011 at 6:28 pm

    Thanks for well structured example, your documentation looks much better than what we find in Facebook.

    I’m using feed dialog to post the feed. and when the logged in FB User posts the feed, the feed dialog will return (Response object) post_id only. but my requirement is to even track all the FB UserIds to whom this feed is posted. Can you help me the way i can collect / track these user ids?

  • satish
    December 19, 2011 at 6:39 pm

    sir, i m face one problem , i m create one page and also create apps, i want to how can Facebook page add new tab app name ..

  • Tony Nguyen
    December 20, 2011 at 3:09 pm

    You save my life. Thanks a lot man.

  • Muhammad Ashfaq
    January 3, 2012 at 8:00 pm

    how r u dear?
    I made facebook application and integrated with a page tab, i add invite friends button and it works perfectly but the issue is when invited user click on invitataion, the link take the user tp application canvas page(, I want the user to redirect my page application.
    is it possible???
    I would be a great pleasure to get help from You


  • Shinu Thomas
    January 5, 2012 at 5:26 pm

    I want to share a link on my wall and my friends wall.I have used this code

    $ret_obj = $this->facebook->api(‘/me/feed’, ‘POST’,
    ‘link’ => ‘’,
    ‘message’ => ‘Friendly Songs….!’
    echo ‘Post ID: ‘ . $ret_obj[‘id’] . ”;

    The link is successfully sharing on my wall.But it is not showing on my friends news feed.In facebook document they mention that because of link parameter it is not updating on friends feed.Is any other way to do this .

  • Paul Evans
    January 11, 2012 at 11:45 pm

    Thank you! I have struggled for 2 days to get PHP SDK and Auth working, maybe with out of date tutorials. It seems Facebook has changed everything twice since I was last trying to develop an app for it.

    I have got it working now using your files, so I can use it to get mine running now.

    Thanks again.

  • Ralph B.
    January 18, 2012 at 9:27 pm

    I have searched a bunch of misleading and outdated sources just to get the authentication to work properly. And your code worked!! Thanks !!

  • DamJan
    January 20, 2012 at 7:17 pm

    Hello,what i need to do to enable auto stream publis?
    Can someone explain me and write that part of code?

  • Pauline
    January 27, 2012 at 1:45 pm


    I followed your codes and both old and new tutorial. And it will prompt the user to log in and allow. But how do I add the publish button and invite in my game? And where does the codes store the user’s data? Please help me. Its urgent.

    • Daniele
      January 31, 2012 at 8:02 pm

      you should open the page home.php i guess…. there you can choose the operation to test

  • Daniele
    January 31, 2012 at 8:05 pm

    I have a problem to get this app working…
    the first page to open is index.php, that call fbmain to check authorization and login, right?

    I don’t understand the “baseUrl” and “appBaseUrl”. Shouldn’t them be the same? index.php?

    I can’t start the application..

    thank you

  • Murat
    February 1, 2012 at 12:44 am

    Hi, Mahmud
    Very great and helpfull tuturial thank you so much and we wont new tuturial about 3.1.1 sdk.
    Take care.

  • Harry
    February 2, 2012 at 2:09 am

    Hello, Great tutorial! A quick question:

    How can I store in my database the text that user types on the stream publish facebook popup? (third tab of your demo).

  • Vanty
    February 3, 2012 at 11:57 pm

    Nice tutorial! it is very used full.
    thanks Mahmud

  • ikbhal
    February 20, 2012 at 6:05 pm

    i was looking for some code to connect and see , post stuff
    its great, keep posting some more articles on graph api, score api, credits api please

  • Willy Chagas
    March 16, 2012 at 12:29 am

    This Demo contain Error

    Erro 501 (net::ERR_INSECURE_RESPONSE): Erro desconhecido.

  • rossi
    March 23, 2012 at 5:19 pm

    do you have a compilation of your scripts to download ???

  • xuanchien
    March 25, 2012 at 6:07 pm

    I want to show “Total friends” and show list photo on myapp, but it not work.
    This is my code, can you help me?

    $me = $facebook->api(‘/me/friends’);
    echo “Total friends”.sizeof($me[‘data’]).””;

    echo ” Friends collage”;
    foreach($me[‘data’] as $frns)
    echo “”;


    • André Vieira
      April 3, 2012 at 1:46 am

      Same problem!

      I’d like just to show my friends on my website: id (in order to link to direct to fb, name e avatar).

      I’m using php, i’ve already created the app and I have the APP_ID and the SECRET key.

  • turgut
    March 28, 2012 at 5:12 am

    hi mahmud.

    ı need your help about this app.

    ı made an application using by your app.

    but there is a cross domain cookies problem in safari.

    if ı use link in “home.php” its redirecting to index.php.

    ı cant go

    it works other browser. problem is safari.

  • kiran
    April 3, 2012 at 10:20 am

    hi, it was so helpful i made the facebook word done but i need to integrate linkedin to website
    means users need to login from there linkedin account can u pls help me out

  • suchi
    April 6, 2012 at 12:32 pm

    Dear friend,

    Please describe of facebook logout code. My problem is after login not logout facebook account on my site.

    Pleaseeeeeeee any body help


  • Ahmed Elsayed
    May 2, 2012 at 9:34 am

    Hello sir you are great I wish you can tell us how we can create fb app like game and make who use this app when start useing it message appear in his wall how we can do that?
    and how we can make for example cron job to send every 24 hour a post too?
    please tell me thanks in advance

  • Al Akmad
    May 8, 2012 at 4:30 pm

    Hi Mahmud, this is such a wonderful post! It’s a big help! Please post more tutorials like this

  • Jako
    June 6, 2012 at 5:18 am

    If it can help, i had the infinite refresh issue too.
    Just before break all stuff around, I found…
    I have a whitespace in my secret key string variable…
    Good job mahmud !

  • Thomas Moraes
    June 10, 2012 at 12:54 am


    I added my app_id and app secret id..

    2 problems:


    1 –

    I tested out the demo on my server… once i click login to facebook.. it pops up to accept application and permite secure info for the app..that`s great.. but as soon as it refreshes back .. it says “Error establishing a database connection”. Why does that appear?

    2 – If a refresh the page even after it appears “Error establishing a database connection” everything appears great!! So when i go to Invite friends… the popup appears..i check my friends and click on invite.. nothing else happens… none of them receive an invite to the app..what could i be doing wrong?

    Here is the URL that im testing:

    Thanks again!

  • Shishir Ahmed
    June 27, 2012 at 5:05 am

    Hi Mahmud

    last two weeks I am expending almost my half of day in your web site. Thank you sharing some good skill. I have a question. how can I retrieve my page list that I am admin in facebook. please help as I am working one facebook application using PHP

    Thank U 🙂

  • Andy
    July 8, 2012 at 10:55 pm

    AWESOME!! Thank you sooooooooo much!!
    Works Great!!!

  • ricardo
    July 9, 2012 at 9:06 pm

    hello first of all thanks for the tutorial, but I have a problem

    When you run this code

    newInvite function () {
                      FB.ui receiverUserIds var = ({
                             method: ‘apprequests’
                             message: ‘come on man checkout my application. visit ‘
                      function (receiverUserIds) {
                               console.log (“IDS” + receiverUserIds.request_ids);
                      / /

    in the console says

    that the variable is undefined


  • Alex
    July 15, 2012 at 10:56 am

    Thanks! Great tutor!

  • Filipe Pawlik Leite
    July 26, 2012 at 9:00 pm

    Hi Mahmud

    Firt thank you veryy much for this and others amazing posts you do like many others say god bless you!

    I would like to know if you can help me with some problem, i´m develping an app and it´s a page no on canvas, i install your code and work perfect to get the authorization of the user but i can´t make your on the facebook page the code that verify if user likes or not and redirect to different content or pages

    It work if i don´t use the new sdk but i dont get the permision of the user and when invite friends the user on save is 0.

    This is the code…

    $signed_request = $facebook->getSignedRequest();
    $like_status = $signed_request[“page”][“liked”];

    I redirect to this page (in page tab) after login (in cavas)

    I don´t know if this is the best prectice, this app is very simple

    1. Log + get permision to be able to save uid
    2. Check if user already like the page and make redirection depending on case
    3. Invite friends and save on db the request
    4. Redirect to page you are done

    Very sorry boring you but my boss wants to kill me and i´m new into this

    Thank you very much
    Best Regards

  • Ankita
    July 28, 2012 at 3:00 pm


    Job Profile is as below,

    Description = PHP Programmer

    1. Job description : PHP programmer required who will be responsible for creation and maintenance of our website

    3. Graduation stream : IT (PHP programming is must)

    4. Technical skill sets : PHP, Mysql

    5. Salary : As per Experienced & industry standards

    6. Rounds of interview (selection procedure) : 2 rounds, first round is HR round and second is technical round

    7. Job Location : Charkop, Kandivali (W)

    8. Joining Date: Immediately

    Thanks & Regards,
    Email :-

  • sudheesh
    September 20, 2012 at 12:33 pm

    Hello mahmud
    i am getting this error while loading my FB application , what would be the problem.
    API Error Code: 191
    API Error Description: The specified URL is not owned by the application
    Error Message: Missing redirect_uri parameter.

  • top10tricks
    October 9, 2012 at 1:33 pm

    /feed api dont work until now

    i keep trying but it says improper content to post only ‘Hello World’

  • chandrasekar
    October 11, 2012 at 3:23 pm

    i can send application requests those i add in tester roles, but i could not send all my friends.i dunno what i have to change in settings page.

  • anne
    November 3, 2012 at 10:31 pm

    Thank you for the tutorial!! But Is there a reason why DEMO link does not work any more?

  • Hao
    November 29, 2012 at 6:10 am

    Thats awesome tutorial!Thanks a lot
    Got one question for you,How can I replace ‘home.php’ to my ‘index.php’,I already have a website,and need to put my website into that frame…

  • kananimaulik
    December 1, 2012 at 6:20 pm

    how can i configure facebook application for this please give me some tutorial or link sir.
    i m new for this….

  • rohman
    March 8, 2013 at 9:05 am

    assalamu alaikum …. slm dr indonesia
    bagaimana jika pada file fbmain.php itu saya tidak pakai url… muncul pesan error yang bunyinya “terjadi kesalahan”… mohon bantuannya….
    kirimi saya balasan di

    terima kasih…

  • angry video game nerd
    April 4, 2013 at 6:42 am

    I am in fact thankful to the holder of this site who has shared this great piece of writing at

  • nice blog
    April 4, 2013 at 4:15 pm

    What’s Going down i am new to this, I stumbled upon this I have found It positively useful and it has helped me out loads. I’m hoping to
    give a contribution & aid other customers like its aided me.
    Good job.

  • games generator games tool games facebook games facebook hack
    April 4, 2013 at 11:11 pm

    Wow that was unusual. I just wrote an very long comment but after I clicked
    submit my comment didn’t appear. Grrrr… well I’m not
    writing all that over again. Anyhow, just wanted to say wonderful blog!

  • coupons
    April 5, 2013 at 9:50 am

    I’m not that much of a internet reader to be honest but your blogs really nice, keep it up!
    I’ll go ahead and bookmark your website to come back later on. Many thanks

  • Yvette
    April 12, 2013 at 11:26 pm

    Wonderful work! This is the kind of info that are meant to be shared across the internet.
    Disgrace on the seek engines for now not positioning this
    submit higher! Come on over and discuss with my web site .
    Thank you =)

  • CM
    April 26, 2013 at 5:33 pm

    Thanks for all you work and thoughful comments.

    However, there’s something I don’t understand. There are lots of people here saying that some parts of their apps are working or not working, while I cannot even get a valid user.

    I did log and get the permissions, but then I get this zero user and the app starts bouncing from my server to Facebook and vice-versa.

    I haven’t made any changes to your code, apart from the app credentials and url addresses. Why am I unable to get a valid user?

    Might it be something on my server?

    Any help would be very welcome, because I’m going mad.

  • Frankie
    June 1, 2013 at 1:50 pm

    svfvlfvlksdfvn ldsf nvd;kfnva’odfnva’ofnfv

  • acne killer
    June 11, 2013 at 4:18 am

    Acne Killer is more likely to have hormone-related Acne Killer.
    No treatment works for everybody, but it wasn’t. That blockage is generally caused by an allergic reaction. It may also be prescribed controlled substances, such as the face and thereby spreading infection.

  • lina mora
    June 18, 2013 at 2:49 pm

    if this APP really works as said…. SHOOOOOOT i would be logged in exfinity..

  • bathmate review
    July 7, 2013 at 6:53 pm

    I discovered your website web webpage on the internet and check some of your early posts. Keep on the superb operate. I lately further encourage RSS feed to my MSN News Reader. Searching for toward reading much more by you down the line!

  • randka
    July 19, 2013 at 1:19 am

    Everything is very open with a precise clarification of the challenges.

    It was truly informative. Your website is very
    helpful. Thanks for sharing!

  • mobile apps
    July 20, 2013 at 11:36 am

    Thanks for finally writing about >Graph API &
    IFrame Base Facebook Application Development PHP SDK 3.0 | Thinkdiff.

    net <Loved it!

  • weight loss elite
    August 4, 2013 at 2:25 am

    Your style is unique in comparison to other folks I’ve read stuff from. Thanks for posting when you have the opportunity, Guess I will just bookmark this page.

    September 7, 2013 at 2:20 am

    of course like your website however you have to test the spelling on quite a few of your posts.
    A number of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will definitely come back again.

  • dailynews
    September 12, 2013 at 6:03 pm

    I must show some thanks to this writer for rescuing me from this condition.
    Right after researching throughout the the net and getting suggestions that were not
    pleasant, I thought my entire life was done. Living minus the strategies to the difficulties you have solved by means of the short article is a serious
    case, as well as the kind which may have adversely
    affected my career if I hadn’t discovered your web site.
    Your good capability and kindness in handling a lot of things
    was useful. I am not sure what I would’ve done if I hadn’t encountered such a step like this.
    It’s possible to at this time relish my future.
    Thanks a lot very much for your impressive and results-oriented guide.

    I won’t be reluctant to refer your web site to anyone
    who should receive direction on this topic.

  • ar500 handgun targets
    September 17, 2013 at 6:27 am

    Thanks for the auspicious writeup. It in truth used to be a amusement account it.
    Look advanced to far brought agreeable from you! However, how can we communicate?

  • anonse towarzyskie
    September 26, 2013 at 7:06 am

    It is the best time to make some plans for the future and it’s time to be happy.
    I’ve read this post and if I could I desire to suggest you few interesting things or tips.
    Maybe you can write next articles referring to this article.
    I want to read even more things about it!

  • Oakley sunglasses
    September 26, 2013 at 6:34 pm

    I really like it when individuals come together
    and share views. Great website, keep it up!

  • Buford
    September 27, 2013 at 11:11 am

    Its such as you learn my mind! You appear to understand a lot about this,
    like you wrote the guide in it or something. I feel that you can do with a few
    % to pressure the message home a little bit, however instead of that, this is
    wonderful blog. An excellent read. I will certainly be back.

    October 3, 2013 at 12:10 am

    Thanks for the good writeup. It in reality was a enjoyment account
    it. Lookk advancfed to more brought agreeable from you!
    However, how can we be in contact?

    October 7, 2013 at 6:24 am

    In a tight race, the i – Phone 4 built on the success oof its predecessors to set the pace for
    smartphones. But if you have installed any software of ylur
    choice, be removed during the reset. Clicking on those optiolns then allows you to chsnge the overall look of the
    battery, fonts aand backgrounds.

  • Chloe
    October 7, 2013 at 1:09 pm

    Nice post. I learn something totally new and challenging on blogs I stumbleupon everyday.
    It will always be exciting to read articles from other
    authors and use something from other sites.

  • Norris
    October 7, 2013 at 1:10 pm

    If you are going for best contents like me,
    only visit this web page all the time since it
    presents feature contents, thanks

  • como agrandar el pen矮aturalmente yahoo
    October 9, 2013 at 10:54 pm

    What i doo nott realize is if truth be told how youu are not
    really a lot more neatly-appreciated thasn you
    might bbe now. You’re very intelligent. You understand thus considerably when it comes
    to this topic, made me in my opinion consider it from numerous
    numerous angles. Its like men and women are not involved except it is one thing
    to accomplish with Lady gaga! Your individual stuffs excellent.
    At all times care for it up!

  • anti aging aesthetics duluth
    October 10, 2013 at 4:38 am

    Hi there! Someone in my Myspace group shared this site with us so I came to check it out.
    I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers!

    Exceptional blog and terrific style and design.

  • kohlscareer
    October 19, 2013 at 5:55 am

    If you want to take a good deal from this paragraph
    then you have to apply these methods to your won website.

  • Phil
    October 19, 2013 at 11:31 am

    My relatives every time say that I am wasting
    my time here at net, but I know I am getting knowledge daily by reading thes good articles.

  • Cristiano Leoni
    November 3, 2013 at 3:58 pm

    I followed this tutorial and created two successful apps with it in the past.

    Trying the third app today, but strangely after double-and-triple-checking the settings of the app and the config in the fbmain file I have got:

    on Mozilla Firefox: after Authentication, the browser apparently is on Facebook’s app page, but actually is getting redirected again and again inside the IFRAME from the app to itself on a loop, always changing the “code” parameter (traffic inspected with Fiddler2)

    on Chrome: empty app page and no redirection at all.

    Any hint to solve it is greatly appreciated

  • amit ray
    November 9, 2013 at 10:03 am

    Try to update your code as facebook may ban it. While trying your demo i canceled the request twice but the pop up was not redirecting to my home page instead it was asking me again and again than automatically i was redirected to report app page by facebook. I didn’t complaint about the app and closed that window. But it may be a problem later. Please check that.

  • James Scott
    June 1, 2014 at 4:11 am

    hey! thank you Mahmud. this is a great tutorial.. it helped me very much… I just got an issue. I adapted your source code in order to use it with my own application. but when a user tries to access my application there is no authorizatio window prompting. I don’t know what to do. I assume the issue may be caused by the access token i used but i don’t really know what to do to fix it.

    • mahmud ahsan
      mahmud ahsan
      June 1, 2014 at 11:34 pm

      This is very old tutorial. Please checkout Facebook’s document for latest change.

  • NuRetnol
    July 22, 2017 at 1:03 am

    Great post.

Comments are closed here.