This blog - now archived - is read-only.
New blog: Mohammad Emran Hasan.

Quick start on new Facebook PHP SDK (IFrame based)

This post is more than couple 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!

210 thoughts on “Quick start on new Facebook PHP SDK (IFrame based)

  1. Mahmud Ahsan

    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?

  2. Pingback: Webs Developer » Emran Hasan’s Blog: Quick start on new Facebook PHP SDK (IFrame based)

  3. DJo

    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

  4. alexl

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

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

  5. Daniel

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

  6. Daniel

    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.

  7. Donavan Moore

    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.

  8. Emran Hasan

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

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

    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!

  10. Avi

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

  11. Venki

    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.

  12. Jason

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

  13. Emran Hasan

    @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 !

  14. Yuval

    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?

  15. Paolo Fix

    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!

  16. Mark

    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.

  17. Emran Hasan

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

  18. Pingback: SDK pour Facebook | traffic-internet.net

  19. Marcel Bariou

    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

  20. rutherford

    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

  21. cifroes

    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?

  22. Lyndon

    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

  23. Lyndon

    @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->getSession();
    $me = null;
    // Session based API call.
    if ($session) {
    try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
    } catch (FacebookApiException $e) {
    error_log($e);
    }
    }

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

    Hope that helps.

  24. Isha

    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.

  25. Emran Hasan

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

  26. Rauf

    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

  27. Pingback: How to get started using the new Facebook Graph API

  28. Pingback: New Facebook PHP SDK | Ansermot.ch

  29. Ernesto

    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?

  30. Emran Hasan

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

  31. rutherford

    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?

  32. emanuel

    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?

  33. Fabio

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

    1. Emran Hasan

      @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!

  34. Andrew

    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!

    1. Emran Hasan

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

  35. Wing

    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!

  36. mick

    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?

    1. Emran Hasan

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

  37. Serg

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

    result of the first script;

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

    1. Emran Hasan

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

  38. goldfuz3

    i cannot get the value of $me somehow. i can get the uid, but not the name:
    $me = $facebook->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?

    1. Emran Hasan

      @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()); .

  39. srinivas

    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.

    1. Emran Hasan

      @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

  40. David

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

    1. Emran Hasan

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

  41. Michael

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

    1. Emran Hasan

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

      $url = $facebook->getLoginUrl(array(
         'canvas' => 1,
         'fbconnect' => 0,
         'req_perms' => 'publish_stream'
      ));
      
  42. sk0rp

    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?

    1. Emran Hasan

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

      $url = $facebook->getLoginUrl(array(
         'canvas' => 1,
         'fbconnect' => 0,
         'next' => 'YOUR_URL_HERE'
      ));
      
  43. Eka

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

    1. Emran Hasan

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

  44. Dan Wellisch

    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

  45. JuhaniH

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

  46. Dan Wellisch

    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

    1. Emran Hasan

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

      $uid = array('123', '456');
      $fields = 'first_name, last_name, pic_square';
      $friends = $facebook->api(array(
          'method' => 'facebook.users.getInfo',
          'uids' => $uid,
          'fields' => $fields
      ));
      
  47. Pingback: Develop Facebook Apps with Code Igniter and Facebook Graph API « Ph@ntoM

  48. Eric

    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.

  49. Eric Gribkoff

    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']));

  50. Wing

    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.

  51. Sridhar Devulkar

    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.

  52. Jimmy_Page

    @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

  53. William

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

  54. Yasir

    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

  55. marketmike

    Emran,

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

    Am I missing something?

    Mike

  56. Usman

    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.

  57. Usman

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

    Thanks for the nice tutorial.

  58. vishal

    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

    1. Emran Hasan

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

  59. chaiwa berian

    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.

  60. David

    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’
    ));

  61. Ian

    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!

  62. YuanMoJin

    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.

  63. Shailendra

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

  64. Imran

    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.

  65. Emran Hasan

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

  66. Emran Hasan

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

  67. Emran Hasan

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

  68. Emran Hasan

    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 !

  69. Johnny Loke

    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->api(array(
    'method' => 'facebook.users.getInfo',
    'uids' => $uid,
    'fields' => $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' => $fbconfig['appid'],
    'secret' => $fbconfig['secret'],
    'cookie' => true,
    ) );

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

  70. Jose

    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

  71. Zeno

    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?

  72. Ivan R.

    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.

  73. theone

    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

  74. pepelton

    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?

  75. Gustavo Crespo

    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

  76. lionel

    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

  77. Ramiro

    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

  78. Mariano

    Thanks!!! its a mini great tutorial!

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

  79. Fire

    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!

  80. Narek

    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.

  81. Roee Aizman

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

  82. Claudia

    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(

  83. KualaBear

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

  84. Rachna

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

  85. Emran Hasan

    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:

    header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
    
  86. Boboy Buloy

    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

  87. Nand

    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

  88. Nick

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

    Thanks alot :)

  89. mohamed

    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

  90. Emran Hasan

    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.

  91. Cris Casinillo

    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

  92. gevork

    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

  93. iamrookie

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

  94. RIccardo

    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

  95. Johnny Loke

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

  96. RIccardo

    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

  97. App Developer

    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.

  98. Adam

    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] => => 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.

  99. nalinder

    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

  100. nalinder

    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.

  101. Ravisankar

    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.

  102. Ravisankar

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

  103. Sandeep sagar

    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.

  104. Feisal

    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.

  105. Dhiraj Chandra

    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

  106. Scott Henderson

    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!

  107. Scott Henderson

    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.

  108. Scott Henderson

    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.

  109. Scott Henderson

    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″

  110. Scott Henderson

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

  111. Scott Henderson

    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");

  112. waka llorca

    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] => => 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 ) ) ) ) )

  113. Jet Rico Bañas

    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.

  114. Voideo

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

  115. Ravi

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

  116. Dibyendu

    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

  117. juicy

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

  118. Zeeshan Zakaria

    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.

  119. Jac

    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

  120. Xavier

    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

  121. jimbob

    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

  122. dan

    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.

  123. Emran Hasan Post author

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

  124. nil

    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.

  125. sirin k

    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?

  126. online beauty magazines

    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.

  127. Irulappan

    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.

    1. Emran Hasan Post author

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

  128. kaila jignesh

    Call to undefined method Facebook::getSession() in /var/www/personal_jignesh/fb/main.php on line 13

  129. Pingback: web business