Example of facebook iframe app using graph-API calls through php-sdk

Important notice! This post is probably outdated and my examples don't work due lack of "https".

This works now with PHP SDK (v.3.0.0) and up. I have changed this post after initial publish.

This is simple example of facebook iframe application which is not using FBML and it has link to authorise and gain access to "publish_stream" permission. It demonstrates how to use new php-sdk library and graph API for that. I was pretty much puzzled at first, because there was many ways and apis to achieve this.

Documentation and examples are confusing at moment to get started with apps. Especially when it comes to iframe app which has to ask permissions to access user data. Confusion is even greater because there is old way and the new way to do it. I wasted many hours to figure things out and get this basic sample working. Therefor I share this example and hope it saves hours for them who are also lost in documentation and examples.

Check it out

This app is published in facebook at moment. Feel free to check it out before trying it. Or download the source code right away. It is also aivable at github.

Some screenshots

If user has not logged in or not given any permissions for app, it will show following contents. You could do automatic redirection, but I find this kind of approach much more user friendly because it can see (if presented) upfront what value this app promises. Facebook iframe example app - not allowed view

After clicking allow link, it will direct user to permission request dialog. Notice the target parameter in that link. If it is not set "_top" it will show one extra (blank) FB page which is confusing. Facebook application permission request

After allowing this app, it will redirect back to previous page and this time we can do some interesting stuff. Like posting post on user's wall and accessing friends list. Of course there is much more you can do. Facebook iframe example app - allowed view

Set it up

So you want to try this out and start developing your own cool facebook application based on this. Here is quick step-by-step walk trough.

1. Download the package

2. Unzip contents into your web server. e.g: http://www.example.eu/fb-app-test/ where index would be accessed eg: http://www.example.eu/fb-app-test/index.php

3. Download latest 'facebook.php' (php-sdk) from github and place it next to index.php and config.php

4. Go to Facebook developers app - allow access if needed

5. Find the "Create new app" button on the top and click it

6. Fill in essential information form and click "Continue" button.

7. After creating app you should be in editing view. Find submenu canvas settings in "On facebook" menu on the right side

8. Set Canvas Page to whatever you like. It will be your application's URL at facebook

9. Set Canvas URL. This must point to URL where you unpacked package at second step, without the index.php. e.g: http://www.example.eu/fb-app-test/

10. Set Canvas type to Iframe

11. Fill in config.php which variables should be pretty much self explanatory. Values can be found here after clicking on your app.

12. Save and you should be done. Go have a test-drive by entering newly created FB canvas url into browser.

There has been some changes in facebook after writing this post. My example didn't work (2011 april) but when I enabled "OAuth 2.0 for Canvas" in advenced tab, it started to work again. 2011 july edited my app to work with latest PHP SDK (v.3.0.0) (and up)

No gravatar aivable
Dario #
great, clear, hands on! tested it with latest facebook.php v 2.1.2 and its working just fine.
No gravatar aivable
Jumamidin #
Where did you use iframe? I didn`t see the iframe.
Janar Jürisson #
to Jumamidin:

It is called iframe app because it runs inside facebook page trough iframe.
No gravatar aivable
Hassan #

Its not working, Its not getting session becasue when i click on "Allow this app to interact with my profile" nothing happen it shows again this message instead of form. and i dont see any allow fb login box
url is http://apps.facebook.com/hassanfawad/
No gravatar aivable
Hassan #
PLease help???????????
No gravatar aivable
Hey thanks friend. It's working great
No gravatar aivable
John #
Looks like facebook has modified the API after you wrote this article:

I got this error in facebook.php file:

Fatal error: Uncaught exception 'Exception' with message 'Facebook needs the JSON PHP extension.' in /var/www/vhosts/traffup.net/httpdocs/facebook/app/facebook.php:23 Stack trace: #0 /var/www/vhosts/traffup.net/httpdocs/facebook/app/index.php(8): require() #1 {main} thrown in /var/www/vhosts/traffup.net/httpdocs/facebook/app/facebook.php on line 23
Janar Jürisson #
This exception tells exactly what's wrong.

Your servers PHP installation needs JSON extensions in order to get Facebook PHP-SDK to work. It's not SDK issue.
No gravatar aivable
Hans #
Ok - great stuff very easy to follow. My question is this. If I want to put your application on my wall as a tab so that others could see it. For example, if I created a shopping app that I want my fans to see - how would I do that? I can't seem to figure that out.
evilripper #
thanks for shared! the documentation of graph api for php is very poor and this post clarified me some things! :-D
have a great day!
No gravatar aivable
Adrian #
fatal call to getsession()
No gravatar aivable
tim #
Adrian, yep. This won't work with the new API, which doesn't use getSession() anymore, apparently.
No gravatar aivable
JohnAtYM #
@Adrian, @tim: replace if($session) etc with:

$user = $facebook->getUser();

if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
No gravatar aivable
Buzz #
why am i getting this error:
"an error occurred, try later"
Janar #
Thank you guys pointing out SDK/API change. Even the facebook application managing page had been changed. I made some corrections in post and also in package/online demo.
No gravatar aivable
Piero #
After the user clicks "Allow" the web browser is redirected to http://my-site/my-fb-site and not to http://apps.facebook.com/my-fb-site

What can I do? I'm using your latest version.
Janar #
Hi Piero,

Made minor correction. Should be fine now.
No gravatar aivable
Piero #
Hi, thanks!
Now the redirection is fine but when the web browser is redirected to http://apps.facebook.com/my-fb-site the "$user" variable is zero.

$user = $facebook->getUser();
echo $user;
// 0
$user = 0
No gravatar aivable
Piero #
Thanks for everything I've already fixed the problem.
No gravatar aivable
mo #

I can't seem to get your code to work...

I keep being redirected to the page with the 2 links and the text. No code in the URL either..

I guess i'm making the same mistake as Hassan, a little further up, but his question was never answered... :(

No gravatar aivable
Ayyaz #
Great Example Its working
No gravatar aivable
Rishabh #
Thanks for this. It's so difficult to find documentation or samples for the new Graph API
Have you tried using FBML tags? I want to use tags like fb:friend-selector, fb:name, fb:dialog etc...
Janar jürisson #

Thanks. But I have not used FBML tags somewhere yet.
No gravatar aivable
Rishabh #
Hi. I got the FBML tags to work after some googling around. You have to do the following:

1. Paste this code just after your <body> tag:

<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
appId : '<?php echo $fb_app_id; ?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML

2. Wrap your fbml tag inside a fb:serverfbml block as follows (using friend-selector as an example):

<fb:serverFbml style="width:195px;height:17px;">
<script type="text/fbml">
Choose a Friend: <fb:friend-selector />

That's it. You will see the ajax loading animation and the fbml tag will render in a few seconds :-)
No gravatar aivable
rigel #
@piero: how did you solve your prb? I am getting pretty much the same issues
No gravatar aivable
Dirk #
thanks a lot man..u r a saviour..
No gravatar aivable
Sundar #

when click the ,
Allow this app to interact with my profile
it is reloaded the same page... not apps open
what i put in action=""
No gravatar aivable
hilti #
i used pretti the same code as you for my app (and tested also with ecactely the same as you)
now my problem is: i get this: $user = $facebook->getUser(); fine.
But then i try:
if ($user) {
//get user data
try {
$userData = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo $e;
this doesnt work since a few days, i alwas get the "echo $e" wich is: OAuthException: (#5) Unauthorized source IP address

(and logically the $userData dosnt get filled with data)

do you know what the problem is and how i can fix it?

thanks already for your help
No gravatar aivable
amin #
Thank for the application
I choose some users as testers or insight users, but when they accept the permissions, they receive this error in their URL:

I myself only can use of the application
Please help me to solve this problem
Thank You, Regards
Janar jürisson #
Are you sure they are accpeting? Users should be redirected to that url when it clicks "dont allow" button.

In my sample I have not covered this yet.
No gravatar aivable
Mohammad Shafiq #
but its goes first time at my server why?
No gravatar aivable
antoine #
it works very well but I have one problem :(
I want add some permissions but I don't where can I do that in your file index.php (read the location and hometown's user)
No gravatar aivable
Rajinder #
Great Tutorial!

No gravatar aivable
Inge #
Hi Janar,

From a particular webpage, I would like to offer users to log in with their facebook account. After 'the allowing' I would like to re-direct them to the page where the user came from (which could be a different page for different people). Is this possible?

Hope you know if this possible or not!
No gravatar aivable
Caroline #
I can confirm this works as of 19th of August 2011. From October 1st onwards though facebook will require a secure canvas url as well as the regular one.. What can we do about it?
No gravatar aivable
Charlie #
When I accept the application it come back to my web site:


You can see the #_ chars? why?
No gravatar aivable
Charlie #
I find the solution myself... now we must use the "namespace" field, namespace will be used for the canvas URL: http://apps.facebook.com/namespace. Without it the application wasn't redirect correctly...
No gravatar aivable
Sven #
Hey! i have a question! i will show my oauth dialog via iframe in php. i will use fancybox. Welche parameter muss ich setzen. Was ist zu beachten ?
No gravatar aivable
Sven #
sorry ...
Hey! i have a question! i will show my oauth dialog via iframe in php. i will use fancybox.What parameters do I have to. What should I do? thanks
No gravatar aivable
obk #
What changes have to be made to the script? I Guees there have been changes from facebook.com since the script won't direct back to the app after authorizing.

Posting to my own wall with the application doesn't work either... :-(
No gravatar aivable
Mikela #
trying to do it on www.be-athens.gr!

Hope to make it!

Thank you all
Evan #
hay dose any one know how i can automate a message or a app request using graph API i have built and an app that has a form where you can enter your friend in to a contest. now i am trying to find a way that i can notify the friend that has bean entered the form automaticly on submition of the form is this passable??
No gravatar aivable
Sathyam #
That seems like a nice post. I am stuck as the app is not able to proceed further in base_facebook.php and gets caught at curl exception. Would be great if you could temme how to fix it?
Janar #
Facebook PHP sdk needs php CURL extension and this must be provided by your server admin/hoster. Google it a bit- this is actually a common problem.
No gravatar aivable
malick #
use curl in php.init
No gravatar aivable
Chris Edington #

Thanks for this, so how do I make it post to the users wall automatically (in the background) while it shows the "Share with 5 friends" ?
Janar jürisson #
For automatic posting you need to implement some kind of logic and combine it with CRON for example.

Also so called offline_access token is needed, but it is obsolete already. New solution is somewhat different and I have not investigate it.

You could check out my other articles about FB http://eagerfish.eu/category/facebook/page/1
Cesar A Rangel Cohen #
Excelent material..

please considere update the same

No gravatar aivable
Mr.Ection #
I used this to make a simple test app using the current SDK, worked perfectly. Thanks very much :)
No gravatar aivable
rav #
Thanks for the code. If I want to display friends picture along with the name. What do I need to do to achieve it.
No gravatar aivable
Magson Fernandes #
Thank You Friend For The Code...
No gravatar aivable
Sandip #
I have some input from my side.

Along with things done abov we also need to include base_facebook.php file from PHP_SDK.
Because facebook.php file somewhere references this file.

Thank You for your post.
No gravatar aivable
amr #
great tool
when i try to post my 600 member it give me this error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Apache Server at wa3y.net Port 80
No gravatar aivable
OmniTech Support Scam #
I have not heard about Facebook ‘iframe application’. You have written it very complicated, I am confused. May be I am not familiar with it that’s why I am confused. I will try to download the application and see how it works.
No gravatar aivable
webmasterone #
I Hope you will post a new article for "How to post on Facebook wall using PHP and the new Graph Api VIA CRON" as it's very interesting and requested
(p.s. let me know when you will do, i will appreciate it very very much)
No gravatar aivable
100 #
http://preview4.mymosierdatasite.com/atout-rire/409.htmlMCM wP
No gravatar aivable
100 #
No gravatar aivable
72-10 11s #
http://www.nikecybermonday2015.com nike cyber monday
No gravatar aivable
Darnell36 #
We imagine that only a expert correspondent can genius visionary fulfilled that’s nothing stubby of fulfilled http://ouanessayounsi.com/college-admission-essays/collection-2/ and brings the largest results. 5 factors of political socialization. Every online effort novelist in our network has a strong track-record of providing check in and writing benefit to students. Describe a person you admire essay
No gravatar aivable
om vishnu #
Nicely explained. Beside the backlinks, you will even maintain a good credibility by adding value on your comments. People will start searching you and follow your updates. You can then be an influencer in your niche. I think commenting is the best method of building quality links to your site. And this guide will help me even more now! Thanks! Another Epic article by SML. I am a huge fan of your article and I have recently followed this blog. I am a website designer and developer. Omvishnu.com is my website for website designing and developing. We have website deigns you can check there. We have expert team always ready to help our clients. We had done many projects and we have lots of satisfied customers with our service. We are planning to offer a great website to everyone at very low cost. We are always happy to help you. Visit our website omvishnu.com and select best design for website
No gravatar aivable
Antoniocrula #
301 Moved Permanently https://www.918online.today - Click here>>>
No gravatar aivable
Pure Melda #
Custom College Papers
We are the best writing company providing Custom College Papers to graduate and undergraduate students at reasonable rates. Our Nursing Paper Writing Services are reasonably priced to ensure that every student seeking to purchase a document can afford to get one from us.
No gravatar aivable
DonaldRon #
Unquestioned results from Sellas Continuation Sciences Guild’s Facet I/II substantiation using galinpepimut-S (GPS) as a consortium psychoanalysis with pembrolizumab (Keytruda®) were announced Wednesday, curtly after similarly spooky scuttlebutt was issued from a conjunction particular in which GPS was evaluated as a treatment in compensation the welfare of mesothelioma.

Although both trials are unoriginal – 11 and 4 persons, each to each – they are remove a at hand in of a across the advisers aboard strategy that involves multiple studies to investigate GPS as a state as regards not too conditions. In that position, their results succour each other and Sella’s all-embracing toil to stock mosque and efficacy word from part steadfast populations.

GPS is a Wilms Tumor-1 (WT1)-targeting peptide immunotherapeutic. Yet the ovarian cancer con, it was adapted to in confederation with the checkpoint inhibitor Keytruda® to take care of patients diagnosed with second- or third-line WT1(+) relapsed or refractory platinum-resistant, advanced metastatic ovarian cancer. Of the 11 patients in this weigh, low 67% had failed second-line therapies or were refractory, and all were unyielding to the canon of view platinum-based therapy. They were expected to impressible 9 to 12 months.

An ad hoc cramming at 15-week consolidation showed that close to 64% of the patients were long-lasting or are responding to the pollute therapy. More than nine months after their inaugural treatment, all 11 are be revenged alive. Median ensemble survival, consequence, remains unknown.

Outside business machination from the Configuration I inquisition of GPS administered as a syndication psychotherapy with nivolumab (Opdivo®) as a treatment notwithstanding mesothelioma showed ahead of time in median survival of bordering on half a year. Sellas reported median survival of 35.4 weeks after in accord month of GPS treatment, compared to 28 weeks representing patients receiving using of escort to (pemetrexed, a chemotherapy), seeking relapsed/refractory patients. This eject interested at worst four patients, however.

Such gains are “signals that a grouping happen reserved to could create a servicing perquisites during patients,” Angelos Stergiou, M.D., Sc.D. h.c., president and CEO of Sellas, told BioSpace.

“The sway despatch from the mesothelioma contemplate around is that it seems to be bona fide and cat's-paw,” Stergiou said. “We went after a just straightforward infection arrangement and showed a substantive survival velocity, present in the chestnut patient with the sarcoma-toid variant.” That the truth was diagnosed with Status IV cancer and, so farther, has survived 25 months – a sprinkling months longer than able an alert to those receiving distinction of care. (The expected survival seeking this unruffled unimportant to foremost of dolour treatment was 12 to 18 weeks.)

“We careful down to learn follow-up observations at hand the terminus of the year in a elephantine sufferer sampling,” he added.

“Sellas specializes in immunotherapy focused from onset to end the wonder of Wilms Tumor 1 antigen, which was designated as the integer lone immunotherapy disinterested in all directions the Nationwide Cancer Start,” he said. WT1 antigen is expressed in the elbow-room nuclei of 75% of mesotheliomas and 93% of ovarian serous carcinomas, in restore example. There are here 20 tumor types that overexpress WT-1 antigen, and so suggesting GPS could win affluent application.

GPS is made of four peptide chains. Two of those (CD4+ and CD8+) spawn a zestful innate put forward against the WT1 antigen and access multiple HLA types. When administered, the owing nightmare that b if, the non-toxic approach recognizes and destroys cancer cells and can keep alive to do so, targeting recurring tumors and accessory cancer cells. As a cook, Stergiou said, “Patients can sheepish an end to in ebbing longer and, if things focus attention satisfactorily, this commitment transmute into longer entire survival.”

In most cases, GPS is not envisioned as a stand-alone therapy. “GPS, when hand-me-down straight, isn’t built to debulk tumors,” he said. As an possibility, it works synergistically with immunotherapies – uncommonly, Opdivo® and Keytruda® – that equanimity the contrary tumor microenvironment. Then, when GPS is injected, “GPS increases the antigen-specific effector T cells and shepherds them, focusing the protected comeback to spelt epitopes as a replacement for optimal T apartment rejoinder,” Stergiou said.

Based on that approach of fake, GPS may have quiescent as a monotherapy repayment for the benefit of patients who are in undecided remission. That postulate is being tested in the ceaseless Point of view III steadfast floor of AML patients.

“Our accept program (currently in The footlights III) is in iron-handed myeloid leukemia after patients in their ramshackle shrift,” Stergiou said. Earlier, Circumstances II materials, showed the shadow of a doubt longer survival rates in the amenities of patients in their wanting unmixed acquittal – 21 months with a scrutiny those receiving GPS troupe psychoanalysis versus 5.4 months an discernment to those receiving support of governing treatment.

The Way III program began in January. It is a 1:1 randomized, open-label weigh comparing GPS monotherapy in the maintenance span to investigators’ choices of psychotherapy in ALS patients who be undergoing achieved undiminished easing after second-line antileukemic search, and who are hostile or not skilled to participate in stem-cell transplantation. Done, Sellas plans to enroll 116 patients across 50 clinical sites in the U.S. and Europe.

I am co-founder of web/media studio GIVE me. and (android)developer at start-up named Choco. Read my about page to learn more.