Quick start on new Facebook PHP SDK (IFrame based)

May 3, 2010
This post is more than 1 year old. It solved the issues when the SDK was first released and facebook had lack of documentation. However, now facebook has very rich set of documnetation and you should follow that instead!

The new Facebook API has already spread over the application developers and if you’re like me, you’ve already got your hands dirty to see how this new thing works. If you have tried to follow the documentation to authorize/get session in your canvas application, it is likely you have already hit roadblocks. Well, I am no savior but I have glued together a few clues and got it working for myself.

I am assuming that you have already created your application by following the Getting Started section from the official documentation. Also, this is for IFrame based applications only.

Enough talking, let’s get some code.

Step 1: Get the new SDK

Download the new SDK from github. We will only need the facebook.php file from the src folder. In our project directory, let’s create a folder called “lib” and put the file there.

Step 2: A configuration file

Let’s now create a configuration file to store our facebook configuration. Let’s name it config.php. Here goes the source:

<?php

define("FACEBOOK_APP_ID", '113795715321151');
define("FACEBOOK_API_KEY", '064baf5fb98de050cd7b9a001ca1988b');
define("FACEBOOK_SECRET_KEY", '430f43c01f6dfe02c284b4545976f9ce');
define("FACEBOOK_CANVAS_URL", 'http://apps.facebook.com/emran-test-app/');

Step 3: Application Main Page

This file will be the main entry point to our facebook application. It just instantiates the facebook object, sets the configuration and checks for a valid session. If it does not find a valid session, it redirects to the login page. For first time visitors, it will be the authorization page. On later requests, the operation will occur in the background – without any user interaction.

<?php

include_once 'lib/facebook.php';
include_once 'config.php';

$facebook = new Facebook(array(
    'appId'  => FACEBOOK_APP_ID,
    'secret' => FACEBOOK_SECRET_KEY,
    'cookie' => true,
    'domain' => 'phpfour.com'
));

$session = $facebook->getSession();

if (!$session) {
   
    $url = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0
    ));

    echo "<script type='text/javascript'>top.location.href = '$url';</script>";

} else {

    try {

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

        $updated = date("l, F j, Y", strtotime($me['updated_time']));

        echo "Hello " . $me['name'] . "<br />";
        echo "You last updated your profile on " . $updated;

    } catch (FacebookApiException $e) {

        echo "Error:" . print_r($e, true);

    }
}

You might be wondering – it’s pretty straight-forward, so what’s the catch ? Well, to be honest, the documentation does not have the “canvas” parameter mentioned anywhere which does the primary magic here. Also, if you do not use the javascript trick, then you end up with an authorization dialog with full facebook UI within the iframe itself (see below).

CodeIgniter Version

Here is the CodeIgniter version of the above example. The significance is that CodeIgniter removes the values from the $_GET super global – which is required for the library to work. We thus re-populate it on the constructor ourselves and start a session to share data among subsequent page visits.

<?php

include_once APPPATH . 'libraries/facebook-php-sdk/facebook.php';

class Test extends Controller
{
    private $facebook;

    public function __construct()
    {
        parent::__construct();
        parse_str($_SERVER['QUERY_STRING'], $_GET);
        session_start();
    }

    public function index()
    {
        $this->facebook = new Facebook(array(
            'appId'  => $this->config->item('facebook_app_id'),
            'secret' => $this->config->item('facebook_secret_key'),
            'cookie' => true,
            'domain' => 'phpfour.com'
        ));

        $session = $this->facebook->getSession();

        if (!$session) {

            $url = $this->facebook->getLoginUrl(array('canvas' => 1, 'fbconnect' => 0));
            echo "<script type='text/javascript'>top.location.href = '$url';</script>";

        } else {

            try {

                $uid = $this->facebook->getUser();
                $me = $this->facebook->api('/me');

                $updated = date("l, F j, Y", strtotime($me['updated_time']));

                echo "Hello " . $me['name'] . "<br />";
                echo "You last updated your profile on " . $updated;

            } catch (FacebookApiException $e) {

                echo "Error:" . print_r($e, true);

            }
        }
    }
}

Hope I am able to help a few people.

Cheers!

There are 206 comments in this article:

  1. 4/05/2010Alam says:

    Very Very Impressive Tut. Find you online atlast

  2. 4/05/2010Ron says:

    Though after a long time, Excellent post Emran vai.

  3. 4/05/2010Tsuka says:

    thanks dude, finally it’s working. :s

  4. 4/05/2010Mahmud Ahsan says:

    This is really helpful article for new sdk. I like it and it solves my problem when I use this as is. But when I tried to integrate this code/logic in CI then authentication problem doesn’t solve. Do you have any suggestion for CI using your tips?

  5. 4/05/2010Webs Developer » Emran Hasan’s Blog: Quick start on new Facebook PHP SDK (IFrame based) says:

    [...] look at how to get started with interfacing your PHP script with Facebook, take a look at this quick guide from Emran Hasan. The new Facebook API has already spread over the application developers and if [...]

  6. 4/05/2010Mahmud Ahsan says:

    Thanks emran vai for your another solution that you give me through chat for CodeIgniter framework.

  7. 4/05/2010Emran Hasan says:

    All you are welcome and I am glad it worked for you. And here goes the Code Igniter version for the CI lovers: http://codepad.org/V2pw7x0u

  8. 4/05/2010Jim says:

    You don’t mention how to specify which permissions you want

  9. 4/05/2010DJo says:

    Hello,

    Thanks for this tut !

    I’ve got an additionnal question, I was using the old FB API, but I don’t understand how to use publish method or requesting access with the new API.
    Do you have an example for this ?

    Thanks a lot

  10. 5/05/2010alexl says:

    @Jim
    as req_perms parameter to getLoginUrl, e.g. after ‘fbconnect’=>0

    e.g. “req_perms => “email,offline_access”

  11. 6/05/2010Daniel says:

    Hello, the !session section does not display anyting in my case, the echo just doest not work
    Any ideas what coud it be?
    Thanks.

  12. 6/05/2010Daniel says:

    Hello, the problem was resolved, however there is another problem and is that getLoginUrl is returning http formated url, this is instead of ..&val=something is returning $amp;val=someting.
    This is causing that several address got not recongnized for the http url interpretar, with facebookk returning an error “Invalid next url” code = 100.

    The easies way to fixit is doing a replace although a professional solution should be.

  13. 6/05/2010Donavan Moore says:

    Great code.
    Seems to be a difficult thing to do (write a Facebook iframe app).
    Question: What do we do if the user right clicks and selects “Open frame in new tab”?
    Do we allow them to use the app outside Facebook or use some redirect magic to put them back in the Facebook iframe?
    Just wondering if anyone has any thoughts on that.

  14. 6/05/2010Emran Hasan says:

    @Moore: Actually it’s not that difficult – you just need to spend some time :) Also, we do need to use redirect to put the user back into Facebook. Something like this:

    [php]
    if (!isset($_GET["fb_sig_in_iframe"])) {
    header("Location: " . $facebookCanvasUrl);
    exit;
    }
    [/php]

  15. 6/05/2010itay noy says:

    Very helpful post, just helped me finalize the authentication hell i was in for three days.
    I hope Facebook people are going to document all this soon. but instead they will probably change it again. well enough bitching, THANKS!

  16. 6/05/2010Avi says:

    Great post, was specifically looking for the ‘canvas’ parameter trick – thanks! :)

  17. 6/05/2010Venki says:

    Emran, You are AMAZING!
    Your caught significant deficiencies on fb.
    This guy Naitik Shah must be fired.
    This company with 400 Million users, puts out a half baked api with loads of bugs, with no proper documentation and talks like sometin great.
    We should write a sensible open source social app and dump people like these.

  18. 6/05/2010Emran Hasan says:

    @Venki: Heh heh…I have sympathy for this Naitik guy though :)

  19. 6/05/2010Jason says:

    It’s weird…I can’t get it to work so that session is true…and I can never get the line to print out my name, etc. I’m using this code pretty much exactly…I just added some more stuff to the bottom…which shows because it’s outside of the if-else statement and has no FB function calls in it.

    Also, it’s confusing to use FACEBOOK_API_KEY for the ‘appId’ (and I did check that it shouldn’t be FACEBOOK_APP_ID…it didn’t change anything for me).

  20. 6/05/2010Emran Hasan says:

    @Jason – Not sure why it’s not working for you. Make sure your application configuration is proper and your script can read the $_GET / $_COOKIE properly. If needed, send me email with more specific problem and I might be able to help. Thanks !

  21. 6/05/2010Yuval says:

    Hi Emran. This is a very useful post which helped me figuring out how to work with the new API – so thanks.

    A question: do you know if and how is it possible to use FBML now with the new API?

  22. 7/05/2010Paolo Fix says:

    Hi, helpfull code.
    I’m making some test.

    If I execute code when application has been already allowed it works perfectly. If I remove myself from application and re-execute the code, I caught exception FacebookApiException

    What workaround?

    Hi guy!

  23. 7/05/2010Mark says:

    I can’t tell you how much this helped me, writing Facebook apps sucks. They really need to be a bit kinder to their developers and have documentation that’s correct. Maybe take a leave out of the new MSDN.

    Anyway, I had a problem where I have a promotion, that needs to be initiated from within a tab, and the javascript redirect wasn’t working correctly, so I used the echo ”; in it’s place. And everything works perfectly now.

    Thanks for your help.

  24. 7/05/2010Emran Hasan says:

    @Paolo: My example is a quick-start so naturally it does not have all the bells and whistles :) The exception is thrown as the library tries to make calls to the facebook with the session stored in the cookie – however, as the application authorization is revoked from the facebook UI – these calls will fail. This cookie is valid for 2-hrs, so for this situation you can catch the exception and show proper message to the user (maybe ask him to wait for a couple hr – or provide a tutorial on clearing cookie). After 2 hrs, the cookie should expire and the app go to the login url to fetch new session.

  25. 7/05/2010SDK pour Facebook | traffic-internet.net says:

    [...]  Quick start on new Facebook PHP SDK (IFrame based) (0 visite) [...]

  26. 9/05/2010Marcel Bariou says:

    Thanks for your work Emran,
    Some hope on start, Ask correctly for login , but after login, it fails on
    $me = $facebook->api(‘/me’);
    with Error:FacebookApiException Object

    Some hints ?

    Thanks

    Marcel

  27. 9/05/2010rutherford says:

    Hi, looking into the new api for the first time and while I copied your code and am creating an iframe app I got an error msg telling me to set my connect base domain. I did this and somehow then got the authorisation page but when I authorised it I got an empty response from chrome:

    Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error.

    how should I look to debug this or better yet do you know why that would happen? And can you explain why I had to set a connect base domain when the app is a canvas iframe one?

    cheers for any help

  28. 9/05/2010cifroes says:

    Hi,

    This solution doesn’t work in IE, because it doesn’t set the cookies. This means that you add another page (index2.php) and follow a link to it, the user is redirect AGAIN to the auth page and trying to set new cookies

    Any solutions?

  29. 9/05/2010Lyndon says:

    Hi,
    Excuse my confusion, I’m very new to developing facebook apps, I don’t have any experience with the previous API’s or functionality. What exactly is the problem that canvas=1;fbconnect=0 fixes? I’ve tested it both ways and my app (at this stage just very simple, does nothing more than display the friends data) behaves the same way regardless of those parameters. Just trying to understand why, rather than blindly doing it.
    Using the javascript redirect, rather than a header redirect, cause the auth dialog to be full page, rather than inside the iframe as you describe. Is it not possible to have the auth dialog inside the iframe? (without the full facebook UI obviously) or is full screen just the way it’s done?
    Cheers,
    Lyndon

  30. 9/05/2010Lyndon says:

    @Paolo @Marcel The example code in the official sdk describes the problem you might be seeing… Basically, although you may get a valid session object from getSession(), it may be invalid (due to expiring, removing the app etc.), so until you actually make an api call, you don’t know if it is valid or not. So you need to make an api call (in the example access /me) and catch the exception to see if the session is valid. From the example:

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

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

    Hope that helps.

  31. 10/05/2010Isha says:

    Hi,

    I copied your code and followed your instructions, but I ran into two problems. The code currently directs facebook users who aren’t logged in to facebook correctly to the login page. Thereafter, which I assume should direct to the authorization page for new users to the application, but instead I get this:

    Allow Access?
    Invalid Argument
    The Facebook Connect cross-domain receiver URL () must have the application’s Connect URL () as a prefix. You can configure the Connect URL in the Application Settings Editor.

    Also I get this only when I set the application’s Migration tab to disable new data permissions. Otherwise I will get this after logging in to the application:

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

    Is there any workaround for this? It’s been a really frustrating search for a solution, what with facebook’s API changes and data permission changes whatnots. Otherwise, I think your solution provided the best possibility for my application to get started.

  32. 10/05/2010Federico says:

    Very helpful, thanks!

  33. 10/05/2010Emran Hasan says:

    @Isha: The connect URL is important here because the iframe apps are more or less a connect app – as it runs directly from your server in iframe. it will need connect to get facebook data. Your app might be very small as of now but as soon as you’d like to add functionality where fbml will be used, invite form will be needed, etc – then you’ll need connect. So best would be to configure it now. Start with setting the Connect URL same as your canvas URL and if you still face problem, write to me in details and I will help you out.

  34. 10/05/2010Rauf says:

    Hi to everyone.
    I’m really annoyed struggling with facebook api and hope someone can help me…
    Connecting to facebook is not a problem, but how can I get statistics for campaign?
    I’ve looked through sources of the new facebook api, and couldn’t find there anything referring to the ads.getCampaigns and ads.getCampaignStats methods described in the documentation http://wiki.developers.facebook.com/index.php/API#Ads_API_Methods
    Did anyone accomplishe this before?
    Or may be somebody know how to do it?

    Thanks in advance

  35. 11/05/2010How to get started using the new Facebook Graph API says:

    [...] How to use the new PHP SDK in your facebook Application [...]

  36. 11/05/2010New Facebook PHP SDK | Ansermot.ch says:

    [...] Quickstart (IFrame based) Share and Enjoy: [...]

  37. 12/05/2010Jasman says:

    nice share..
    can you give me an sample invitation using scripts sdk-php?
    thank you

  38. 13/05/2010Ernesto says:

    Hi

    I copied the code (only 1 file, right? the CodeIgniter Version) , replacing the 2 fb keys and I get this errors:

    Warning: include_once(APPPATHlibraries/facebook-php-sdk/facebook.php) [function.include-once]: failed to open stream: No such file or directory in \index.php on line 3

    (even if I change “libraries/facebook-php-sdk/facebook.php” for “facebook.php” the error remains)

    and

    Fatal error: Class ‘Controller’ not found in index.php on line 5

    ??? What Im doing wrong?

  39. 13/05/2010Emran Hasan says:

    @Ernesto: If you do not use CodeIgniter framework then you should try the first way.

  40. 16/05/2010rutherford says:

    Just an update on my issue – I found creating a new app got rid of the ‘connect url not set’ issue but now when a user authorises the app the response url is far too long with lots of info repeated. In fact it’s so long my host’s firewall blocks the request and I don’t see it my end.

    Anyone have any experience of fixing the query string facebook creates after a user authorises an app?

  41. 19/05/2010emanuel says:

    okay,.. i figured it out,.. I replaced the line of text that you had with:
    header( ‘Location: http://virtualrealestates.net/index.shtml‘ ) ; … and it worked!!!

    but now i have a few more problems,…1) the first time it gets authorization and redirects to my site,.. it opens the site in a full window and not into the FB canvas,.. I did notice someone else asked the same question, above, but i didnt see an answer to it.

    2.) My second question,.. my original website is to wide,.. I was wondering if their was a script/code that I could use to rescale inside the FB canvas,.. I have looked and looked.. i have tryed a few… but it gets me nowhere… is it even possible?

  42. 19/05/2010Fabio says:

    Hi,
    I have a really great problem with the new PHP-SDK (sound strange, uh?). I have a form in the main page of my FB apps and wher I post the variables, but on the action page the session var is not kept for some reason, the page is reloaded by the first part of your script and obviuosly my post vars disappear.

    How can I pass the session var throug different pages of an FB application

    (PS: this new PHP SDK are driving me crazy!!!)

  43. 19/05/2010Andrew says:

    Thank you very much for publishing this. It has been extremely helpful. As of today (19 May) we started to notice that users who are not logged in get the following warning message if they try to navigate to a canvas page (this message appears on the login screen):

    The Facebook Connect cross-domain receiver URL ({canvas callback URL}) must have the application’s Connect URL ({canvas URL}) as a prefix. You can configure the Connect URL in the Application Settings Editor.

    We have the app set up as follows:
    Canvas Callback URL: URL of the app on our server
    Canvas URL: http://apps.facebook.com/{canvas page}
    Connect URL: http://apps.facebook.com/{canvas page}

    Other than this warning message, the app works fine – users can still log in and the app loads and operates normally. We are not loading or referencing xdreceiver.htm on our pages.

    thoughts?

    Thank you!

  44. 22/05/2010Wing says:

    I have repeat your tutorial again using approach 1 (as I am not using the mentioned application framework)… and it works…. so please kindly remove my previouos post. Thx for your great tutorial!

  45. 22/05/2010buzzknow says:

    excellent article especially for CI part :)

    thanks a lot

  46. 23/05/2010mick says:

    Great code, thanks! I’ve used it in my Graph API iframe app and it’s working great in IE8, IE7, IE6, FF and Chrome. I’m getting a problem with Safari though: when I visit the app the getSession() and getUser() calls succeed, but the api(‘/me’) throws an error indicating an invalid session. At this point perform a javascript redirect to my app, expecting Facebook to clear the invalid session. Unfortunately this doesn’t happen, and I end up in a loop, perpetually redirecting back to my app.
    I can work-around by changing Safari preferences to be more permissive about accepting cookies. In Preferences->Security I change the Accept Cookies setting away from its default value of ‘Only From Sites I Visit’ to ‘Always’ and everything works OK.
    Obviously I don’t want all my users to have to make this change – anyone had a similar experience or got any suggestions?

  47. 23/05/2010Serg says:

    $facebook->api(‘/me’) not working

    result of the first script;

    Hello
    You last updated your profile on Thursday, January 1, 1970

  48. 24/05/2010Feroze says:

    please share FBML Based code…

  49. 24/05/2010Feroze says:

    how to use require_login() funcationaliy using new graph api?

  50. 25/05/2010Soheil says:

    Thanks for the help =)

  51. 27/05/2010goldfuz3 says:

    i cannot get the value of $me somehow. i can get the uid, but not the name:

      $me = $facebook-&gt;api('/me');

    returns null.

    as for this

            $updated = date("l, F j, Y", strtotime($me['updated_time']));

    returns: You last updated your profile on Wednesday, December 31, 1969 – which is incorrect date.

    what is wrong?

  52. 28/05/2010srinivas says:

    Hi Emran,

    i just followed you code…
    my app: http://apps.facebook.com/helloworld_udvh

    i earlier had an issue of cross domain, then later i have set the connect url. i am getting a new issue like.
    its actually occuring after getting the login url, when it tries to redirect

    Please any help me, i am stuck from past 1 week to find out what is the problem.

    getting below issues in different browsers, i think i need to do some setting in my server side.. pl. help me

    the issues are as below

    =================================================================
    Issue in IE7 Browser
    =================================================================
    There is a problem with this website’s security certificate.

    The security certificate presented by this website was issued for a different website’s address.

    Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.
    We recommend that you close this webpage and do not continue to this website.
    Click here to close this webpage.
    Continue to this website (not recommended).
    More information

    If you arrived at this page by clicking a link, check the website address in the address bar to be sure that it is the address you were expecting.
    When going to a website with an address such as https://example.com, try adding the ‘www’ to the address, https://www.example.com.
    If you choose to ignore this error and continue, do not enter private information into the website.

    For more information, see “Certificate Errors” in Internet Explorer Help.

    =================================================================
    Issue in Google Chrom Browser
    =================================================================
    This is probably not the site you are looking for!
    You attempted to reach http://www.facebook.com, but instead you actually reached a server identifying itself as a248.e.akamai.net. This may be caused by a misconfiguration on the server or by something more serious. An attacker on your network could be trying to get you to visit a fake (and potentially harmful) version of http://www.facebook.com. You should not proceed.

    =================================================================
    Issue in Fire Fox Browser
    =================================================================
    Secure Connection Failed
    http://www.facebook.com uses an invalid security certificate.

    The certificate is only valid for the following names:
    a248.e.akamai.net , *.akamaihd.net

    (Error code: ssl_error_bad_cert_domain)
    * This could be a problem with the server’s configuration, or it could be someone trying to impersonate the server.

    * If you have connected to this server successfully in the past, the error may be temporary, and you can try again later.

    Or you can add an exception…

    Please any help me, i am stuck from past 1 week to find out what is the problem.

    thanks in advance,
    srinivas.

  53. 28/05/2010David says:

    Is there a way to get the new authorisation done through a normal canvas application – not an iframe canvas app? Been trying for hours to no avail!!

  54. 28/05/2010Rodley says:

    Hi Emran Hasan.

    Thanks, was really helpful.
    :)

  55. 29/05/2010Prasad says:

    Tons of Thanks Emran !!!!
    Very Helpful
    Finally it works for me

  56. 29/05/2010Kay says:

    Thank you bro. Great post. Very simple & helpful.

  57. 30/05/2010Emran Hasan says:

    @David: I haven’t tried that yet, so can’t tell but I guess FB should provide the proper session to the canvas app as POST variables and you’ll then handle it from there.

  58. 30/05/2010Emran Hasan says:

    @srinivas: Sorry for a late reply. The errors you have provided indicates that you are trying to redirect to a page behind SSL but you do not have a valid SSL certificate. Try testing this out on a non SSL page first and if the problem is fixed, then you know what to do :) Cheers

  59. 30/05/2010Emran Hasan says:

    @goldfuz3: It indicates that the SDK is not able to use the session when the call to the api method is made. You can check by adding this just on top of the $me call to see:

    var_dump($facebook->getSession());

    .

  60. 30/05/2010Emran Hasan says:

    @Feroze: There is no require_login function in the new SDK, that is precisely what we are trying to achieve here by doing the redirection ourselves. In the old SDK, the require_login function did very similar to this.

  61. 30/05/2010Emran Hasan says:

    @Serg: Please see my response to goldfuz3.

  62. 30/05/2010Emran Hasan says:

    @mick: I faced this problem with IE though, but later a tip from a friend solved it. The trick is to set a P3P header, although its damn old and has been discontinued, IE seems to have remembered it. Maybe you can try this with Safari as well ?

  63. 30/05/2010Emran Hasan says:

    @Andrew: Thanks. You have to set the Connect URL to the “URL of the app on your server” :)

  64. 30/05/2010Emran Hasan says:

    @Fabio: Are you sue you are referencing the session variable or the POST variable? In order to have proper functionality, you have to make sure cookies are saved in your server and the SDK can read from it. This can be a browser issue so have a look at one of my replies above for a trick. Thanks!

  65. 30/05/2010Emran Hasan says:

    @emanuel: I don’t think you can make the app wider than 760px :P

  66. 30/05/2010Emran Hasan says:

    And thanks to everybody for your comments and appreciation :)

  67. 31/05/2010Michael says:

    How do you request extended permissions using the php SDK after the user has logged in?

  68. 31/05/2010fred says:

    great job, you save my day, thank you!

  69. 2/06/2010sk0rp says:

    Thx for the great guide. Unfortunatelly I’ve got some problems with getLoginUrl() method.
    I’m trying to make my FBML application working with new API. In the Facebook PHP SDK code the getLoginUrl() method get an url from $_SERVER['HTTP_HOST'] and it of course get my url from my server (Canvas Callback URL). What I need is to redirect after authorization (or canceling that) to my Canvas page not Canvas Callback. Any ideas?

  70. 6/06/2010Eka says:

    hello..

    i have null variable on $me = $facebook->api(“/me”);

    i don;t know why it’s ?

    on var_dump($facebook->getSession())
    have result like this

    array(6) { ["access_token"]=> string(103) “118750864833609|2.nDMm04HPKiSwSoH7WmuExA__.3600.1275832800-100001190678474|inZjummTWzaj1GKcCNtvsjQl9xc.” ["expires"]=> string(10) “1275832800″ ["secret"]=> string(24) “hgsSO2ZCB5YpUxbfSycmCg__” ["session_key"]=> string(58) “2.nDMm04HPKiSwSoH7WmuExA__.3600.1275832800-100001190678474″ ["sig"]=> string(32) “6ce6a470955c3f1cb1aad8d0fd215b50″ ["uid"]=> string(15) “100001190678474″ }

    has anyone have solution about this. ?

  71. 7/06/2010Dan Wellisch says:

    Hello:

    Anybody having trouble using the (old?) users_getInfo() function? I need to get the firstname and last name, given a uid.

    I have changed my calls to $facebook->$api->users_getInfo() from $facebook->$api_client->users_getInfo() but it still doesn’t work….gives me the following error.:

    Call to a member function users_getInfo() on a non-object in…..

    Thanks,

    Dan

  72. 8/06/2010JuhaniH says:

    Thank you!

    Only one in the whole web that helped me get through.
    Web is full of ‘not helping’ tutorials, but yours did the job. ;)

    Again thank you alot!!

  73. 8/06/2010Dan Wellisch says:

    Hi:

    I would like to follow up on my earlier posting. I am just learning my way around and indeed it is hard to code against Facebook as its a moving target.

    The problem I face when using the new SDK versus the old Restful API is this.:

    I can’t use the users_getInfo() API call without getting an OAuth 2.0 error saying that
    the accessToken is not defined. I then tried to use this code to fix this, but it just didn’t work for me.:
    http://sambro.is-super-awesome.com/2010/05/28/facebook-access-tokens-from-canvas-apps/

    Here is more info on authentication: http://developers.facebook.com/docs/authentication/

    But, I really don’t understand how to make use of it.

    My intermediate solution was to use the new facebook.php for authentication and then
    use the old facebook.php (that uses the restful API) for a successful users_getInfo() call.
    I really need to get the firstname and lastname of a friend, given their UID.

    If someone wants to extend Emran’s simple example above (with the black background), and show how to add in the ability to get the firstname and lastname of a friend, given their UID, I think that would be a good example that everybody could use as it is just one of similar functions that we would all know how to use with the new API.

    My intermediate solution as described above, although it works, causes another ugly side effect….so a good solution is needed using only the new API.

    Anybody want to try it and post it here?

    Dan

  74. 8/06/2010Emran Hasan says:

    @Michael: You can send the user to the authorize screen again, this time generating the login URL with the “req_perms” key populated as per you need. Example:

    [php]
    $url = $facebook->getLoginUrl(array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘publish_stream’
    ));
    [/php]

  75. 8/06/2010Emran Hasan says:

    @sk0rp: Yes, you can specify the URL to redirect to like this:

    [php]
    $url = $facebook->getLoginUrl(array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘next’ => ‘YOUR_URL_HERE’
    ));
    [/php]

  76. 8/06/2010Emran Hasan says:

    @Eka: It seems you have a valid session, but the api calls are not working. Can you check if you have JSON and CURL enabled and make sure the api calls are getting through ?

  77. 8/06/2010Emran Hasan says:

    @JuhaniH: Great to know, you’re welcome too!

  78. 8/06/2010Emran Hasan says:

    @Dan: If you have got a valid session and the graph API calls work (like the /me one), then the following code is sufficient for your need:

    [php]
    $uid = array(’123′, ’456′);
    $fields = ‘first_name, last_name, pic_square’;
    $friends = $facebook->api(array(
    ‘method’ => ‘facebook.users.getInfo’,
    ‘uids’ => $uid,
    ‘fields’ => $fields
    ));
    [/php]

  79. 9/06/2010Steffen says:

    Hey Emran,

    thanks for the tutorial. I was trying to get the CI-Version as an iFrame FB-App working. The redirect to the authorizationis working fine, but after that I’m getting a 404
    @
    http://www.server.com/app/?auth_token=af2819faf8axxxxxe93c845c6e3e7eb&installed=1

    and I’m redirected to that page. Any suggestions what could fix that ? (my uri_protocol is QUERY_STRING)

    Could you upload I working version ?

    Thanks,
    Steffen

  80. 15/06/2010wallce says:

    hi all,

    any idea how to use the php-sdk to do a bookmark for my facebook applicaiton

  81. 15/06/2010Develop Facebook Apps with Code Igniter and Facebook Graph API « Ph@ntoM says:

    [...] Source here [...]

  82. 16/06/2010HatLord says:

    Thanks for the superb tutorial, Emran!

    I have a quick question. Do you know what method is this developer using for authenticating his/her app?
    http://apps.facebook.com/qbquiz-ffhmf/

    Thanks.

  83. 17/06/2010Eric says:

    Hello, I copied your code and tried to run it, I got a problem. it keeps reloading with append auth_token in URL. Do you have any ideas? Please, help me out. Thank you.

  84. 17/06/2010Eric Gribkoff says:

    Thanks very much for this! I was having a lot of difficulty getting sessions to work with Facebook and CodeIgniter.

    I did want to point out that line 15 of the codepad file, (http://codepad.org/V2pw7x0u), is not present in the CodeIgniter code here in the blog article on this page. It was crucial to getting sessions to work for me, so thought I would point that out to you.

    It’s this line, right before the call to session_start():

    session_id(preg_replace(“/[^A-Za-z0-9-]/”, “”, $_GET['fb_sig_iframe_key']));

  85. 23/06/2010Wing says:

    how should I migrate my existing FBML appl using the old PHP client to use the new PHP SDK?

    I try the code :
    $facebook = new Facebook(array(
    ‘appId’ => $appapi,
    ‘secret’ => $appsecret,
    ‘cookie’ => true,));
    $session = $facebook->getSession();

    it always give me a null session even if I access my app after I signon to facebook.

  86. 23/06/2010Wing says:

    how can I use this php sdk for FBML application?

    it seems to me that your code is for an IFrame appl only

  87. 25/06/2010Sridhar Devulkar says:

    Great work Emran. Lots of people are appreciating your true effort and I am a happy camper too. Thanks much.

    I have a question though.

    I am able to get the extended permission dialog by adding ‘req_perms’ => ‘publish_stream’, but the problem is, after I authorize, I am redirected to a new page with my Connect URL and all of the fb parameters.

    I am able to avoid the above by setting ‘next’ => ‘http://apps.facebook.com/myapp‘ (not sure if this is the right solution) as a parameter in the getLoginUrl(), but I get to see the session_key, user id etc in the uri. I understand that because it is doing a redirect it needs all of the params to restore the session back, but is there something else that I need to do to so that I can have a cleaner url? and not getting redirected to my connect url?

    Looking forward for a reply from anyone with similar issues.

    Thanks,
    Sridhar.

  88. 28/06/2010Jimmy_Page says:

    @emran +mick +cifroes

    I’am creating an iframe facebook app and i have the same problem of loop on authentication under IE7.
    In this browser, cookies are defined in medium level by default. Auth cookies cannot be written and authentication failed in a beautiful loop.

    As recommanded by Emram, I tried to create a P3P file and added headers but it doesn’t work.

    Emram, could you give us your P3P file ?
    Mick, did you find another solution ?

    Thanks,

    Jimmy

  89. 28/06/2010William says:

    How about iframe session with cakephp, does anybody has working code to maintain iframe session with cakephp?

  90. 30/06/2010Yasir says:

    Hi Cab you tell me how do I can Use facebook.showpermissionsDialog () Like in FBJS in old styles. Or How Can I popup permissions dialog with new Facebook API using Iframe or FBML Version of Facebook App.

    Any Help will be heartdly Prasied.

    Thanks

  91. 5/07/2010marketmike says:

    Emran,

    Setup went smooth but when I load the app I get… Sorry, but you’ve been banned!

    Am I missing something?

    Mike

  92. 8/07/2010El Jeffo says:

    Thanks dude… that darn php-sdk was driving me absolutely insane!

  93. 10/07/2010Usman says:

    Hi Emran Bro,
    I always get the following error without try-catch:-

    Fatal error: Uncaught CurlException: 77: error setting certificate verify locations: CAfile: /usr/share/ssl/certs/ca-bundle.crt CApath: none thrown in /home/halalitn/public_html/fb/facebook.php on line 511

    With try catch the same error is displayed with a long array($e) of info, I didn’t paste it here because it reveals many private info.

    Can you please help me in this issue? I tried a lot but just tired.

  94. 10/07/2010Usman says:

    Thanks Emran Bhai,
    I have solved the issue by adding CURLOPT_SSL_VERIFYPEER => false, to $CURL_OPTS array.

    Thanks for the nice tutorial.

  95. 11/07/2010vishal says:

    Hi Emran,

    Hope you are doing great.

    I just copied the same code given by you and replaced the ID and secret with my own, but unfortunately I get this error when I go to my canvas url:

    Error
    An error occurred with std-lite. Please try again later.

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

    Please help me.

    I apologize if its a very simple fix though I have failed after trying almost all methods of authorization available.

    Thanks,
    vishal

  96. 13/07/2010chaiwa berian says:

    Hello Developers!! i need help. i want to develop an application using PHP on Facebook that appears as a group to which members can be added. my computer is not connected to the internet. is there a standalone SDK and Editor (like Visual Studio ) that i can use to develop my application offline, and upload it to test how it works. help me please. am very new to Facebook App Development Environment. I will appreciate.

  97. 15/07/2010David says:

    Thank you Emran. This article was exactly what I was looking for.

    @Isha: I got the login page to redirect to the request permissions page after login by updating the getLoginUrl array. I added an additional parameter: ‘method’ => ‘permissions.request’

    $url = $facebook->getLoginUrl(array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘publish_stream’,
    ‘method’ => ‘permissions.request’
    ));

  98. 17/07/2010Ian says:

    Hi Emran,

    Launching my canvas page Facebook app is driving me crazy. When I posted its link (http://apps.facebook.com/digitalhitcelebrity) to a fan page wall the FB “attach link” button grabbed the app’s callback url (http://www.digitalhit.com/celebotd) instead.

    The strangeness occurs here: if you go to the the callback url when NOT logged in it redirects you properly to the canvas page. If you go to that url when you ARE logged in you don’t get redirected and the page is not framed by the Facebook branding.

    Using the new php-sdk. Any ideas on how to make sure people are can’t see the callback page unless it’s called from the canvas url?

    Thanks!

  99. 17/07/2010YuanMoJin says:

    Hi,

    Thanks for your tips .

    I ‘d really appreciate that .

    But I have some question .

    I can get session from your hint..

    But I don’t know how I can send notification and email after that in application….

    I used this code..
    $facebook->api_client->notifications_send(‘kwm85@hotmail.com’, “you’ve received a msg from “, ‘user_to_user’);

    But I get this kind of error code ..

    Fatal error: Call to a member function notifications_send() on a non-object

    I know that’s why there is no member “api_client” variable in facebook library .

    I hope your help …

    Regards.

    Yuan.

  100. 21/07/2010Shailendra says:

    Hello nice tut…

    Yaar i have to implement like any user login with facebook and after successfully login that redirect to some another page on my website.

    I mean i want to integrate like any user with facebook login enter intowebsite.

    how to do this???
    reply as soon as possibe..

  101. 21/07/2010Imran says:

    Hi dude,
    Very very useful post. :)

    Can you please share your views about how to test facebook application with localhost using FBML?

    Great Thanks in advance.

  102. 21/07/2010Emran Hasan says:

    @Imran: If you’re making an IFrame based app, then just point the canvas and connect URL to your localhost to work from there – its that simple :)

  103. 21/07/2010Emran Hasan says:

    @Shailendra: Sorry, I do not follow what you mean. Do you mean any user can come to your site and can log in using facebook account ? If that’s correct, then you can have a look at the Facebook connect tutorials in facebook wiki.

  104. 21/07/2010Emran Hasan says:

    @YuanMoJin: The code you are using is from the old facebook SDK and as far as I know, notifications_send function is no longer supported. You can ask for email when users are authorizing your app and can send them email – I think that’s the only way Facebook support right now…anyone ?

  105. 21/07/2010Emran Hasan says:

    Guys, I was out of touch from blog for a couple of days and could not approve/reply to many of your questions. If anyone of you still have questions, please post again or email me directly – I’d try to help :P

    Thanks for all your comments !

  106. 21/07/2010Emran Hasan says:

    @Vishal: Can you post here your application settings and the code ? It would be easier to spot the problem that way.

  107. 22/07/2010Johnny Loke says:

    Great article!

    I manage to get the $me = $facebook->api(‘/me’); result. But when perform the following call:

    $uid = array('123', '456');
    $fields = 'first_name, last_name, pic_square';
    $friends = $facebook-&gt;api(array(
        'method' =&gt; 'facebook.users.getInfo',
        'uids' =&gt; $uid,
        'fields' =&gt; $fields
    ));

    It says “This method call must be signed with the application secret (You are probably calling a secure method using a session secret)” which I already initialized the $facebook with application secret as following:

    $facebook = new Facebook( array(
      'appId'  =&gt; $fbconfig['appid'],
      'secret' =&gt; $fbconfig['secret'],
      'cookie' =&gt; true,
    ) );

    Is there a hack to the include the application secret into the call?

  108. 27/07/2010Jose says:

    When I use:
    $session = $facebook->getSession();

    returns “null”, then I can´t get de User Data

    I don´t know what´s the problem

    Thanks

  109. 28/07/2010Amine Arous says:

    thanks Emran
    it works but i have to do this midification:
    echo “document.setLocation(‘”.$url.”‘);”;

  110. 9/08/2010Juan Fernando says:

    OMG, Thank you so much
    Finally a working solution after hours looking.

    Thanks for sharing.

  111. 10/08/2010Zeno says:

    Hi Emran,

    I followed your code exactly for my iFrame app and the session is never valid. The user can give access to the app and everything, but regardless session is still never valid. Any ideas?

  112. 10/08/2010Ivan R. says:

    Hey Emran, your piece of code is great and works perfectly! Unlike other codes that I have tried, since you use javascript for the loginURL I do not get anymore this annoying “header already sent” warnings.

  113. 11/08/2010Agnel says:

    Simple!!! A very good heads up for a Novice

  114. 13/08/2010theone says:

    i posted a couple of solutions that should help resolve issues with the new api – facebook connect in external site and inside facebook (iframe). fixes issue with IE cross domain cookies as well as with Safari. I use a regular fb:login-button with the new facebook javascript api (all.js file). IE popup window would stay blank after authentication (external connect outside facebook). Safari would not store cookies inside iframe on facebook and would keep refreshing every second. the posts are using the new php sdk but the logic should work for any other technology.

    http://forum.developers.facebook.net/viewtopic.php?pid=257432#p257432

    http://forum.developers.facebook.net/viewtopic.php?pid=256122#p256122

  115. 17/08/2010pepelton says:

    I have the following problem:

    1.I login to FB and access the app’s canvas URL => The app requests permissions correctly and I can see when I’ve updated my status last time

    2. I logout from FB and relogin. Now if I access the app’s canvas URL I get the following error:

    Error:FacebookApiException Object ( [result:protected] => Array ( [error] => Array ( [type] => OAuthException [message] => Error processing access token. ) )

    If I refresh the page I can see info about my status again. But if I logout and login again, the same thing happens.

    Is there a way to prevent this error happening?

  116. 17/08/2010Gustavo Crespo says:

    Hey you man.. !!
    Thanks a lot, you’re really a great guy.
    I am creating a new aplication on facebook and i try many things and nothing works,
    but with your simple code it was past.
    Thank you man !
    DTB
    Ps: sorry for my english, i’m ecuadorian

  117. 21/08/2010lionel says:

    hello everybody,

    i developp a facebook application with codeigniter but i have the same problem with ie7. when i want to acces to my application with ie7 the page reload and it seems the facebook session is null. Maybe a cookie problem or other. I don’t see any great response in all comments. do you have a solution? it drives my crazy

    thank you and sorry for my bad english

  118. 23/08/2010Muhammad Danish Khan says:

    very nice post i was just finding it from 1 hour bcoz i just started FB sCripting.. any other great resource that can be fine plz provide.

  119. 23/08/2010Ramiro says:

    Hi Emran
    Thanks a lot for the article.
    I have a question. I’ve seen lots of iframe applications that automatically redirect to the auth page if not authorized, but with a redirect header. Do you know how this is done? With your way, I have to wait for the iframe to load enough data to execute the javascript. Mafia Wars is an example: http://apps.facebook.com/inthemafia/

    Thanks

  120. 24/08/2010Andrez says:

    Thanks Emran for the tutorial, That’s help me so much :D

    Can I know how to get user’s username?
    Currenlty I got this $me['link'] that includes http://www.facebook.com/{the_username}. But can I get it directly?

  121. 24/08/2010Mariano says:

    Thanks!!! its a mini great tutorial!

    Simple and efficents… it’s runs across browsers!.. the facebook’s samples doesn’t

  122. 27/08/2010Fire says:

    Hi there, great tutorial – I am curious though,

    can you describe how you would implement a facebook login using the https and Oauth 2.0 method using php?

    ie where you have to

    1) Get Authorization Code
    2) Get Access Token

    This would be really helpful!

  123. 28/08/2010Leandro says:

    WOW! Simply, THANKS!!! I search this solution 1 entire day!!!! You saved my live! thakssssssssssssssssssss

  124. 30/08/2010Narek says:

    Hey Friend,

    Thanks for this saver!

    Some personal opinion:
    The fact is that the current facebook example absolutely doesn’t work, and the only thing you can do is blame facebook developers and adhere some popular adjectives to this Naitik guy. But there is a possibility that all those slips had been done intentionally for some reason… I don’t want to believe that facebook developers are full of poop.

  125. 2/09/2010Roee Aizman says:

    Hey Guys.

    I fought with it a lot causing it to work with CodeIgniter:

    1. I put a plugin named facebook_pi.php with all the facebook client inside and above the configuratin:
    false,
    CURLOPT_SSL_VERIFYHOST => 2,

    3. Enable query string in the CI config file

    4. My index begins like:
    public function index()
    {

    $this->facebook = new Facebook(array(
    ‘appId’ => FACEBOOK_APP_ID,
    ‘secret’ => FACEBOOK_SECRET_KEY,
    ‘cookie’ => true,
    ‘domain’ => ‘phpfour.com’
    ));
    $session = $this->facebook->getSession();
    I hope i helped you guys :)

  126. 3/09/2010Claudia says:

    thanks Emran

    I am a newbie… i ran the code above and I get a blank page… any idea??

    it appears to hang.. at this point… $facebook = new Facebook(array(

  127. 4/09/2010KualaBear says:

    Very Helpfull
    simply Works :)
    Thank you!
    got me started at my first day of exploring php-sdk.
    I have a Question
    ive read about the extended authorization
    but what i dont seem to get is where in the code do i implement it, and how .

    Thank You :)

  128. 4/09/2010Rachna says:

    Thanks Emran for the canvas param tip for getLoginUrl.

    I am having a similar problem with facebook->get_add_url() According to the api no params need to be passed in but if i add the get_add_url line below, it gives me a 500 error. Any ideas? thanks. If I remove the line it executes ok. I also tried $url = $facebook->get_add_url(); and same error

    else
    {
    if (! $facebook->api_client->added )
    {
    //handle non-app users by giving them a link to add the application
    echo “Hello, non-app user!get_add_url().”‘>Click here to add this application.“;
    }
    else
    {
    echo “Hello, app user!”;
    }
    }

  129. 10/09/2010Emran Hasan says:

    I’ll be putting a fully working example in a blog post this week so that anyone can see the full example code working. Stay tuned until then guys!

    For IE issues, make sure you’re issuing a P3P header so that IE can trust your cookies. The simplest solution is to have the following code as the first output to browser:

    [php]
    header(‘P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"’);
    [/php]

  130. 10/09/2010Boboy Buloy says:

    not sure why i can’t it to work in codeigniter… i’m using v.1.7.2… somehow a $session is not returned and the page is kept on redirecting to the canvas page in a loop…

    Mr. Emran, you’re enlightenment will be very much appreciated.

    - Boboy

  131. 11/09/2010Binu Mathew says:

    How can i get User Name,and other details of a user using above codE?

  132. 12/09/2010Emran Hasan says:

    @Binu: The $me variable should hold the current logged in user’s details. Have a look here for the list of fields: http://developers.facebook.com/docs/reference/api/user

  133. 16/09/2010John X says:

    Ok i just solved it, delete previous comment plz.
    Thanks anyway for really helpful sites ;)
    Cheers!

  134. 16/09/2010Mark says:

    Thanks a lot! Your post was of great help!!

  135. 17/09/2010Nand says:

    Hi Emran,
    Plz help me, I want to run example.php in examples directory download from github php-sdk.
    I edit appID , secret key, but i get below error.

    Fatal error: Uncaught CurlException: 6: Couldn’t resolve host ‘graph.facebook.com’ thrown in /htdocs/myfb/fblib/facebook.php on line 617

  136. 19/09/2010Nick says:

    Emran, without your solution, I was facing hours upon hours of headache.
    I’d already spent a day on it.

    Thanks alot :)

  137. 22/09/2010mohamed says:

    hi ur code doesnt work in my app. i get this really long message
    Error:FacebookApiException Object ( [result:protected] => Array ( [error_code] => 60 [error] => Array ( [message] => SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed [type] => CurlException ) ) [message:protected] => SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL
    and it goes on further. plz help me out i really want to stick to the iframe approach in order to use jquery and other plugins .
    thx

  138. 23/09/2010Emran Hasan says:

    For those who are getting CURL exceptions, make sure your environment can make CURL calls to the facebook server. It may be a proxy issue, or misconfiguration, etc.

  139. 28/09/2010Cris Casinillo says:

    I followed on the steps but I end up blank page on my apps. Am I missing something? If i put anything above and below the code on step 3, only the above is showing. Help Me…

    Thanks

  140. 29/09/2010Eldad Levi says:

    great! thanks…

    seems so elementary that this post should have been poseted by facebook….

    kinda makes you wonder why they didn’t

  141. 29/09/2010Shane Fernando says:

    Im having trouble loading http://www.facebook.com inside an iframe. This is in my own website i mean. Would u knw what the problem is? It keeps loading only the facebook logo. ne ideas?

  142. 29/09/2010Allen Sun says:

    Hi Erman,

    I don’t understand ‘canvas’ => 1, & ‘fbconnect’ => 0 .

    Please help me, Thank you very much.

  143. 30/09/2010gevork says:

    Hi Emran,
    can you tell me such thing.
    How to post from the application on the wall of the friend .?

    I need to post a notification about the gift which application user sends to his friend who is not yet still using application

  144. 30/09/2010iamrookie says:

    i got the same error as mohamed. i googled about the problem, and somebody suggested to add the following two lines into facebook.php file:-
    $opts[CURLOPT_SSL_VERIFYPEER] = false;
    $opts[CURLOPT_SSL_VERIFYHOST] = 2;
    in the ‘ protected function makeRequest’ method, right after the line of
    $opts = self::$CURL_OPTS;
    now, the problem’s gone. i am just curious why? how it works? and is it safe to do so(to modify facebook.php file)?

  145. 1/10/2010Sascha says:

    I get the same Error and I don’t know what “CURL calls” are… :-( Please help!

  146. 6/10/2010RIccardo says:

    How can i get the picture and others information like friends have accepted the application?
    Old is $facebook->api_client->friends_getAppUsers(); and now?

    Thanks

  147. 7/10/2010Johnny Loke says:

    Thanks Emran for your guide, I manage to create a simple Facebook app with your guide. Keep up your philanthropical act ;)

  148. 8/10/2010RIccardo says:

    Hy i’ve a problem with my apllication, iframe, i have a link on index.php, link, but when i click it the page show this error:

    Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /members/dff/MY_DIRECTORY/src/facebook.php on line 543

    the code in page.php is the same of index.php:
    $facebook = new Facebook(array( …
    $session = $facebook->getSession();
    and so way

    What’s the problem?
    Session?
    Cookie?

    Thanks Erman for guide

  149. 15/10/2010App Developer says:

    The Authorization worked fine, but after the user is authorized the page continually redirects automatically. When I run the app (using your code) from an authorized user, the screen continually flashes, and another redirect occurs every second.

  150. 17/10/2010Adam says:

    Hi Emran
    Everything works good until i reach the $me part, then im saddled with an really long exception error:

    FacebookApiException Object ( [result:protected] => Array ( [error_code] => 28 [error] => Array ( [message] => connect() timed out! [type] => CurlException ) ) [message:protected] => connect() timed out! [string:private] => [code language=":protected"][/code] => 28 [file:protected] => /virtual/f/a/facebookapps.ugu.pl/wishlist/includes/facebook.php [line:protected] => 614 [trace:private] => Array ( [0] => Array ( [file] => /virtual/f/a/facebookapps.ugu.pl/wishlist/includes/facebook.php [line] => 575 [function] => makeRequest [class] => Facebook [type] => -> [args] => Array ( [0] => https://graph.facebook.com/me [1] => Array ( [method] => GET [access_token] => 148724338503052|2.jlaDDPRHOCrmGCx2X9nV_g__.3600.1287327600-100000930134892|sexTLhM77Sk7mFrpCH6pvIBewEs ) ) ) [1] => Array ( [file] => /virtual/f/a/facebookapps.ugu.pl/wishlist/includes/facebook.php [line] => 539 [function] => _oauthRequest [class] => Facebook [type] => -> [args] => Array ( [0] => https://graph.facebook.com/me [1] => Array ( [method] => GET ) ) ) [2] => Array ( [function] => _graph [class] => Facebook [type] => -> [args] => Array ( [0] => /me ) ) [3] => Array ( [file] => /virtual/f/a/facebookapps.ugu.pl/wishlist/includes/facebook.php [line] => 492 [function] => call_user_func_array [args] => Array ( [0] => Array ( [0] => Facebook Object ( [appId:protected] => 148724338503052 [apiSecret:protected] => cc6ddeea833013a9e84198a8f3e2f139 [session:protected] => Array ( [session_key] => 2.jlaDDPRHOCrmGCx2X9nV_g__.3600.1287327600-100000930134892 [uid] => 100000930134892 [expires] => 1287327600 [secret] => dFn2GFzRV4avIiznijYkwg__ [access_token] => 148724338503052|2.jlaDDPRHOCrmGCx2X9nV_g__.3600.1287327600-100000930134892|sexTLhM77Sk7mFrpCH6pvIBewEs [sig] => 9ced9c9b8108df0f35708b123e6b0d05 ) [signedRequest:protected] => [sessionLoaded:protected] => 1 [cookieSupport:protected] => 1 [baseDomain:protected] => [fileUploadSupport:protected] => ) [1] => _graph ) [1] => Array ( [0] => /me ) ) ) [4] => Array ( [file] => /virtual/f/a/facebookapps.ugu.pl/wishlist/index.php [line] => 48 [function] => api [class] => Facebook [type] => -> [args] => Array ( [0] => /me ) ) ) )

    Any thoughts on what can be the cause of this one?? it seems that Curl is timeouting but im not too sure.

  151. 18/10/2010vijay laxmi says:

    Thanks Emran You made my day

  152. 19/10/2010nalinder says:

    Hi. Your code finally working well (in IE 7.0 without redirects). Can you show me how can I do for example invite friends function?

    In my old app i did it like:

    But it doesnt work in your app. I need to use publish stream function as well – can you show us your code with these functions or tell me what I need to do?

    In my app I use AsyncInit:

    window.fbAsyncInit = function() {
    FB.init({appId: ”, status: true, cookie: true,
    xfbml: true});

    };
    (function() {
    var e = document.createElement(‘script’); e.async = true;
    e.src = document.location.protocol +
    ‘//connect.facebook.net/en_US/all.js’;
    document.getElementById(‘fb-root’).appendChild(e);
    }());

    but you cannot use it.. please help me

  153. 20/10/2010nalinder says:

    If im trying to get all friends via:
    $myFriends = $facebook->api(‘/me/friends’);
    foreach($myFriends["data"] AS $key => $value)
    $my_friends[$key] = $value["id"];
    print_r($my_friends);

    It doesnt work in IE 7.0 :( (yes, I have header(‘P3P: CP=”IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA”‘); on first line of the script).

    You promised to show us your code next week (which was 1 month ago). I think, that you can help many people with this (at this time non-existing) application.

  154. 26/10/2010Ravisankar says:

    Thanks Emran. Nice article. Does this new PHP SDK supports make Oauth2.o requests.? Even this new PHP SDK is not supporting asking extended permission from user. If you know how to ask extended permission from user, please share your knowledge.

  155. 26/10/2010Ravisankar says:

    I found out, Pass this params argument to getLoginUrl() function , you will get dialog box with more permissions options.

    $params =
    array(‘display’ => ‘wap’,
    ‘req_perms’ => ‘offline_access,user_photos,user_videos,publish_stream’);
    echo ‘getLoginUrl($params) . ‘”>Login‘;

  156. 29/10/2010Sandeep sagar says:

    Hi i need to get the birthdays of my(user) friends.But i am unable to get that & i got the entire profile of my(user) friends.Please help me to get the birthday also.I am working on java.

  157. 2/11/2010Thanks says:

    Thank you very very much :)

  158. 3/11/2010Feisal says:

    Hi,

    So is no longer possible to log in automatically to facebook through an iframe or lightbox.

    I understand facebook is blocking iframes.

    Is there any solutions available for this, either independlty or through facebook directly.

    I really need your valuable advise on this important issue Emran.

  159. 3/11/2010Dhiraj Chandra says:

    Hey thanks for the real gud post.
    but i have problem that i am facing for quite a time now, i.e. i always get redirected to the login page using the above code.
    i tried logging in though i am already logged in another tab of browser (IE8. After login i get redirected to my Facebook page. is this the correct behaviour? and even after login it always ask redirect me to that login page.

    can you please provide some pointers as in where i am getting wrong.
    Thanks
    Dhiraj

  160. 6/11/2010Dawax says:

    You are the MAN !!!

  161. 7/11/2010Scott Henderson says:

    Emran, I am not having success, yet, on implementing your code. I think it make have to do with my FB App settings (all the various url’s). Would you mind posting ALL of the URL’s within the FB Application screens, which have ANYTHING to do with making your example work?

    Presently, I am getting an Invalid API Key screen.

    Thanks a bunch!

  162. 7/11/2010Scott Henderson says:

    Emran, I just browsed to your FB test app link:
    http://apps.facebook.com/emran-test-app/

    The FB connect dialog came up fine. I clicked ‘Allow’, then tried to post an update, using your Post-to-Stream button. I received the following error:

    “Fatal error: Cannot use string offset as an array in /nfs/c03/h02/mnt/54263/domains/phpfour.com/html/code/emran-test-app/lib/facebook.php on line 32″

    I am in the process of writing my first FB Application (iFrame). You, obviously, are a seasoned expert. Given that… is the FB development platform a ‘moving target’, prone to errors (on any given day)? I would have thought creating an iFrame-based app would be drop-dead easy, given the standard HTML notion of an iFrame. Well, it sure ain’t drop-dead easy and is, in fact, extremely frustrating. I appreciate you’re recognition of this and your attempt to fill the gaps in the FB documentation.

  163. 7/11/2010Scott Henderson says:

    Emran, I just noticed that the Publish Streams test (using YOUR hosted test app, not mine) did, in fact, post to my FB Profile successfully; although, I did get the Fatal Error, mentioned in my last forum post.

  164. 7/11/2010Scott Henderson says:

    Finally! Some degree of success. I finally got your example code successfully hosted on my server. Your emran_test.php ran successfully, although I did receive two FB Warnings regarding date and time code. Here is the entire response that showed up on my FB screen:

    Warning: strtotime() [function.strtotime]: It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/Chicago’ for ‘CST/-6.0/no DST’ instead in /Applications/TWOA_Website/Domains/nickelme.com/canvas/emran_test.php on line 31

    Warning: date() [function.date]: It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/Chicago’ for ‘CST/-6.0/no DST’ instead in /Applications/TWOA_Website/Domains/nickelme.com/canvas/emran_test.php on line 31
    Hello Scott Henderson
    You last updated your profile on Wednesday, February 11, 2009″

  165. 7/11/2010Scott Henderson says:

    Note: the oversight (that I corrected) which allowed your example code to run successfully, was in the path to the config.php file. I had placed that file in the ‘lib’ directory. Thus, I had to correct the path that I had (in emran_test.php) to specify:

    include_once 'lib/config.php';
  166. 7/11/2010Scott Henderson says:

    For anyone else’s benefit, regarding the FB Warnings received for ‘date’ and ‘strtotime’, I eliminated the warnings by adding the following line of code (above the date and strtotime line):

    date_default_timezone_set("UTC");
  167. 8/11/2010waka llorca says:

    I got this error can u help me.

    Error:FacebookApiException Object ( [result:protected] => Array ( [error_code] => 7 [error] => Array ( [message] => Failed to connect to graph.facebook.com IP number 1: Permission denied [type] => CurlException ) ) [message:protected] => Failed to connect to graph.facebook.com IP number 1: Permission denied [string:private] => [code language=":protected"][/code] => 7 [file:protected] => /home/www/wakallorca.freehostia.com/lib/facebook.php [line:protected] => 622 [trace:private] => Array ( [0] => Array ( [file] => /home/www/wakallorca.freehostia.com/lib/facebook.php [line] => 575 [function] => makeRequest [class] => Facebook [type] => -> [args] => Array ( [0] => https://graph.facebook.com/me [1] => Array ( [method] => GET [access_token] => 172692949408703|2.jUsdrb3nOkb3mApaSWvY5A__.3600.1289217600-1359200283|LSXOdjYxQAd0Zjw2pRSKJwuo-ZI ) ) ) [1] => Array ( [file] => /home/www/wakallorca.freehostia.com/lib/facebook.php [line] => 539 [function] => _oauthRequest [class] => Facebook [type] => -> [args] => Array ( [0] => https://graph.facebook.com/me [1] => Array ( [method] => GET ) ) ) [2] => Array ( [file] => /home/www/wakallorca.freehostia.com/lib/facebook.php [line] => 492 [function] => _graph [class] => Facebook [type] => -> [args] => Array ( [0] => /me ) ) [3] => Array ( [file] => /home/www/wakallorca.freehostia.com/index.php [line] => 29 [function] => api [class] => Facebook [type] => -> [args] => Array ( [0] => Array ( [0] => Facebook Object ( [appId:protected] => 172692949408703 [apiSecret:protected] => f70c3afe0f832ac450003899a8d4a109 [session:protected] => Array ( [session_key] => 2.jUsdrb3nOkb3mApaSWvY5A__.3600.1289217600-1359200283 [uid] => 1359200283 [expires] => 1289217600 [secret] => bEJw0UGJ_32zYzWnD9RpYg__ [access_token] => 172692949408703|2.jUsdrb3nOkb3mApaSWvY5A__.3600.1289217600-1359200283|LSXOdjYxQAd0Zjw2pRSKJwuo-ZI [sig] => 79fe70477979abbbcc560e0cca24be41 ) [signedRequest:protected] => [sessionLoaded:protected] => 1 [cookieSupport:protected] => 1 [baseDomain:protected] => phpfour.com [fileUploadSupport:protected] => ) [1] => _graph ) [1] => Array ( [0] => /me ) ) ) ) )

  168. 11/11/2010Jet Rico Bañas says:

    Thanks! I’ll try this now on my new application.
    They never said you can pass and array of:
    “I’m a canvas app and not fb connect”
    parameter to getLogInURL
    that’s what I was looking for. Thanks.

    I’ve always been using fb connect for my apps, so it’s my first canvas development for the new API.

  169. 12/11/2010Aayushi says:

    It helped a lot.!!! thanks

  170. 11/01/2011Voideo says:

    Thank you!
    After the facebook API update is hard to find good resources and this article helped a lot!

  171. 14/01/2011Izdelava internetnih strani says:

    You helped me a lot! Thanks for taking your time and explain this API to newbies like me :)

  172. 30/01/2011tomelders says:

    Thanks for the play by play, it really helped.

  173. 3/02/2011Lapidus says:

    So u use this:
    echo $me['name'];
    to show the name, and it work’s fine :)
    But how can I list some of my friends?
    This page (http://developers.facebook.com/docs/reference/api/user) tells me there is a ‘friend’ option .. how can I put this into an array an get for example my first 5 friends?

    THX, best tut I could’t found on the www =)

  174. 10/02/2011machi says:

    THANKS A LOT!!!!
    this is first tut that really helps a lot!!!

  175. 13/02/2011bmanderscheid says:

    you rock!. Why does facebook make it so hard to write the simplest stuff. Thanks !!!

  176. 15/02/2011Ravi says:

    I made test app. Its working fine if i login with my id and test it but if someone else login with his id and open the same url it does’nt work… can anyone tell me what is the issue with this..

  177. 20/02/2011Dibyendu says:

    Hi,

    I want to know the page id when the facebook application has been added to a fan page. Any idea, How?

    Thanks in advance.

    Thanks

    Dibs

  178. 25/02/2011juicy says:

    Hi everyone struggling authentication redirect loop: try to use newest version of facebook.php! Looping stopped right after when I downloaded latest facebook.php

  179. 6/03/2011Ananda says:

    This was a really interesting post to initiate . Need to some points update here and my post help some one to get clear idea.
    http://anandafit.info/2011/03/06/invite-friends-to-your-site-in-facebook-invite-app/

  180. 8/03/2011Zeeshan Zakaria says:

    All I can say is that may God bless you with all the best. You saved my many days which could have gone wasted in trying to figure out this small little thing, which facebook has no where documented, neither any other blog or tutorials have it mentioned. I had already wasted 3 days trying to figure out whey my OAuth was not working for users’ email addresses. Surprisingly for one of my older applications it was working fine, probably facebook enabled it by default for earlier apps.

    Now my app is fully functional finally.

    Thanks a lot again. Keep up the good work.

  181. 14/03/2011Gus says:

    Dude thank you!. I had been reading the API reference for an entire week!, Thanks!.

  182. 15/03/2011Mohd Yusuf says:

    To those still getting a loop refresh after login, try this:
    http://forum.developers.facebook.net/viewtopic.php?pid=324414#p324414
    I have the same problem, only after I ported the code to my web environment (header, etc etc). Example.php code delivered from PHP-SDK works fine. It was some extra slashes in the cookie that screw up the $session variable.

  183. 25/03/2011Rafael says:

    tanks!!!

  184. 28/03/2011karen says:

    Tks. Was specifically looking for :D

  185. 10/04/2011rubyonrails4ror says:

    Thanks, you saved my hell lot of effort. :-)

  186. 6/05/2011Rob says:

    Thank you!

  187. 6/05/2011Jac says:

    Spent hours trying to find the problem till i saw your page
    also if anyone is having problems make sure that php curl is installed

  188. 11/05/2011Xavier says:

    Using CodeIgniter Version I get :
    Fatal error: Class ‘Controller’ not found in xxxx.php on line 30

    indeed, the word Controller isn’t in facebook.php

  189. 16/05/2011Saville says:

    Been around the internet twice to find a working example – at last there was yours. Well done and a big thanks!!!

  190. 19/05/2011Adam says:

    Thanks for the post, it was very helpful!

    Have you also used JS authentication?

  191. 22/05/2011pavankumar says:

    hey…..thanks a lot.your code clarified many doubts at me……

  192. 24/05/2011jimbob says:

    I copied the code above exactly – all I get is a blank page when I run the app. I am completly out of ideas. Does anyone have any thoughts? Should the main application page above be named ‘index.php’?

    Thanks

  193. 24/05/2011dan says:

    You should mention what version of the SDK this is for. It’s extremely confusing for people that you link to the latest version of the SDK.

  194. 1/06/2011Calebe Aires says:

    This code is Facebook SDK 3.0?

  195. 3/06/2011Emran Hasan says:

    No it’s not. Please follow the facebook documentation instead, that’s recent. Thanks

  196. 10/06/2011joie says:

    Ngrrr.. thank u very much!

  197. 28/09/2011nil says:

    Hi,
    i have facebook.php but code is based on PHP5 version, But i have PHP4 version installed to my server. and this making problem.
    Can you please let me know how to solve this problem?
    OR convert facebook.php file based on PHP4 ( not php5 ) and how we can use that file.

  198. 30/09/2011Abdelkader Soudani says:

    this is a wonderfully written tutorial, thanks for sharing!
    btw anyone having problems with google chrome loading https iframe?

  199. 4/10/2011bdmkteam says:

    hi ,

    is there a way to use facebook php sdk without enabling CURL on php server?

  200. 11/10/2011sirin k says:

    i got 2 question for you from the below part of your code,

    $facebook = new Facebook(array(
    ‘appId’ => FACEBOOK_APP_ID,
    ‘secret’ => FACEBOOK_SECRET_KEY,
    ‘cookie’ => true,
    ‘domain’ => ‘phpfour.com’
    ));

    I this we are setting the attribute “cookie” to “true” why we are doing this? and wht will happend if we are setting this to false?

  201. 2/11/2011naor says:

    hey…..thanks a lot.your code clarified many doubts at me…

  202. 10/11/2011online beauty magazines says:

    I loved as significantly as you’ll receive carried out appropriate here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an nervousness more than which you wish be delivering the following. unwell unquestionably come a lot more formerly again as exactly exactly the same practically a lot often inside case you shield this hike.

  203. 6/12/2011Abhay says:

    Great Usman ! CURLOPT_SSL_VERIFYPEER => false fixed my problem !

  204. 21/12/2011Irulappan says:

    i have aproblem on FBconnect login in chrome browser.after clicking facebook login button in my site it gets my login details and shows only empty pop-up box keeps on openning…. after sometime reload the browser it will show the result of the page..

    please any guide me. how to avoid this much of errors and provide some examples… Thanks in advance.

  205. 23/01/2012Safin says:

    Hi Emran…I need your help to create a facbook application using graph Api and php. if you can help me on this project then contact me to proceed further. Thanks
    Email: safin_24@yahoo.com

  206. 25/01/2012Emran Hasan says:

    Thanks. Please send me the details to my email address: phpfour (at) gmail (dot) com.

Write a comment: