Quick start on new Facebook PHP SDK (IFrame based)
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!

Hello, this is Emran. This is my blog where I (ir) regularly express my ideas and views regarding programming, life, work, and so on. 
04/05/2010 at 12:55 am Permalink
Very Very Impressive Tut. Find you online atlast
04/05/2010 at 4:07 am Permalink
Though after a long time, Excellent post Emran vai.
04/05/2010 at 6:11 am Permalink
thanks dude, finally it’s working. :s
04/05/2010 at 10:08 am Permalink
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?
04/05/2010 at 11:36 am Permalink
Thanks emran vai for your another solution that you give me through chat for CodeIgniter framework.
04/05/2010 at 12:42 pm Permalink
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
04/05/2010 at 1:05 pm Permalink
You don’t mention how to specify which permissions you want
04/05/2010 at 11:02 pm Permalink
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
05/05/2010 at 11:16 am Permalink
@Jim
as req_perms parameter to getLoginUrl, e.g. after ‘fbconnect’=>0
e.g. “req_perms => “email,offline_access”
06/05/2010 at 6:42 am Permalink
Hello, the !session section does not display anyting in my case, the echo just doest not work
Any ideas what coud it be?
Thanks.
06/05/2010 at 10:06 am Permalink
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.
06/05/2010 at 11:58 am Permalink
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.
06/05/2010 at 12:18 pm Permalink
@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; }06/05/2010 at 1:41 pm Permalink
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!
06/05/2010 at 9:36 pm Permalink
Great post, was specifically looking for the ‘canvas’ parameter trick – thanks!
06/05/2010 at 10:54 pm Permalink
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.
06/05/2010 at 11:12 pm Permalink
@Venki: Heh heh…I have sympathy for this Naitik guy though
06/05/2010 at 11:14 pm Permalink
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).
06/05/2010 at 11:20 pm Permalink
@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 !
06/05/2010 at 11:46 pm Permalink
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?
07/05/2010 at 2:44 am Permalink
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!
07/05/2010 at 3:09 am Permalink
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.
07/05/2010 at 5:36 am Permalink
@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.
09/05/2010 at 6:26 am Permalink
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
09/05/2010 at 6:30 am Permalink
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
09/05/2010 at 3:34 pm Permalink
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?
09/05/2010 at 10:23 pm Permalink
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
09/05/2010 at 10:29 pm Permalink
@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.
10/05/2010 at 2:30 am Permalink
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.
10/05/2010 at 3:47 am Permalink
Very helpful, thanks!
10/05/2010 at 5:11 am Permalink
@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.
10/05/2010 at 6:14 am Permalink
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
12/05/2010 at 3:21 am Permalink
nice share..
can you give me an sample invitation using scripts sdk-php?
thank you
13/05/2010 at 4:19 am Permalink
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?
13/05/2010 at 8:13 am Permalink
@Ernesto: If you do not use CodeIgniter framework then you should try the first way.
16/05/2010 at 3:29 am Permalink
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?
19/05/2010 at 7:23 am Permalink
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?
19/05/2010 at 10:44 am Permalink
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!!!)
19/05/2010 at 1:19 pm Permalink
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!
22/05/2010 at 2:55 am Permalink
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!
22/05/2010 at 8:01 am Permalink
excellent article especially for CI part
thanks a lot
23/05/2010 at 2:08 pm Permalink
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?
23/05/2010 at 10:15 pm Permalink
$facebook->api(‘/me’) not working
result of the first script;
Hello
You last updated your profile on Thursday, January 1, 1970
24/05/2010 at 4:45 am Permalink
please share FBML Based code…
24/05/2010 at 4:48 am Permalink
how to use require_login() funcationaliy using new graph api?
25/05/2010 at 3:41 am Permalink
Thanks for the help =)
27/05/2010 at 3:12 am Permalink
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?
28/05/2010 at 5:14 am Permalink
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.
28/05/2010 at 8:32 am Permalink
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!!
28/05/2010 at 11:22 am Permalink
Hi Emran Hasan.
Thanks, was really helpful.
29/05/2010 at 7:33 am Permalink
Tons of Thanks Emran !!!!
Very Helpful
Finally it works for me
29/05/2010 at 4:35 pm Permalink
Thank you bro. Great post. Very simple & helpful.
30/05/2010 at 7:09 pm Permalink
@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.
30/05/2010 at 7:27 pm Permalink
@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
30/05/2010 at 7:30 pm Permalink
@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());.30/05/2010 at 7:31 pm Permalink
@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.
30/05/2010 at 7:31 pm Permalink
@Serg: Please see my response to goldfuz3.
30/05/2010 at 7:33 pm Permalink
@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 ?
30/05/2010 at 7:35 pm Permalink
@Andrew: Thanks. You have to set the Connect URL to the “URL of the app on your server”
30/05/2010 at 7:36 pm Permalink
@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!
30/05/2010 at 7:37 pm Permalink
@emanuel: I don’t think you can make the app wider than 760px
30/05/2010 at 7:41 pm Permalink
And thanks to everybody for your comments and appreciation
31/05/2010 at 7:09 am Permalink
How do you request extended permissions using the php SDK after the user has logged in?
31/05/2010 at 9:49 am Permalink
great job, you save my day, thank you!
02/06/2010 at 10:21 am Permalink
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?
06/06/2010 at 4:52 am Permalink
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. ?
07/06/2010 at 10:38 am Permalink
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
08/06/2010 at 1:01 pm Permalink
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!!
08/06/2010 at 3:24 pm Permalink
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
08/06/2010 at 9:10 pm Permalink
@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:
08/06/2010 at 9:13 pm Permalink
@sk0rp: Yes, you can specify the URL to redirect to like this:
08/06/2010 at 9:14 pm Permalink
@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 ?
08/06/2010 at 9:15 pm Permalink
@JuhaniH: Great to know, you’re welcome too!
08/06/2010 at 9:18 pm Permalink
@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 ));09/06/2010 at 4:53 pm Permalink
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
15/06/2010 at 2:35 am Permalink
hi all,
any idea how to use the php-sdk to do a bookmark for my facebook applicaiton
16/06/2010 at 12:46 pm Permalink
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.
17/06/2010 at 10:26 pm Permalink
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.
17/06/2010 at 11:19 pm Permalink
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']));
23/06/2010 at 6:22 am Permalink
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.
23/06/2010 at 6:34 am Permalink
how can I use this php sdk for FBML application?
it seems to me that your code is for an IFrame appl only
25/06/2010 at 9:54 am Permalink
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.
28/06/2010 at 10:59 am Permalink
@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
28/06/2010 at 7:04 pm Permalink
How about iframe session with cakephp, does anybody has working code to maintain iframe session with cakephp?
30/06/2010 at 8:46 am Permalink
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
05/07/2010 at 8:22 am Permalink
Emran,
Setup went smooth but when I load the app I get… Sorry, but you’ve been banned!
Am I missing something?
Mike
08/07/2010 at 7:52 am Permalink
Thanks dude… that darn php-sdk was driving me absolutely insane!
10/07/2010 at 1:22 am Permalink
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.
10/07/2010 at 2:42 am Permalink
Thanks Emran Bhai,
I have solved the issue by adding CURLOPT_SSL_VERIFYPEER => false, to $CURL_OPTS array.
Thanks for the nice tutorial.
11/07/2010 at 12:13 am Permalink
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
13/07/2010 at 6:53 am Permalink
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.
15/07/2010 at 1:16 pm Permalink
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’
));
17/07/2010 at 12:20 am Permalink
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!
17/07/2010 at 10:04 am Permalink
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.
21/07/2010 at 3:35 am Permalink
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..
21/07/2010 at 4:22 am Permalink
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.
21/07/2010 at 8:36 am Permalink
@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
21/07/2010 at 8:45 am Permalink
@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.
21/07/2010 at 8:48 am Permalink
@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 ?
21/07/2010 at 8:49 am Permalink
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
Thanks for all your comments !
21/07/2010 at 9:44 am Permalink
@Vishal: Can you post here your application settings and the code ? It would be easier to spot the problem that way.
22/07/2010 at 5:44 pm Permalink
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?
27/07/2010 at 1:41 am Permalink
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
28/07/2010 at 6:35 am Permalink
thanks Emran
it works but i have to do this midification:
echo “document.setLocation(‘”.$url.”‘);”;
09/08/2010 at 11:55 pm Permalink
OMG, Thank you so much
Finally a working solution after hours looking.
Thanks for sharing.