From my previous tutorial you already learned how to setup and develop iframe base facebook page application. I named this tutorial iAdvance, because In this tutorial I’ll describe some more advance features but I’ll skip some parts those I already described in my previous tutorial.
Facebook provides some api to access user data and to access this data user must have to authorized your application. Otherwise you can’t call facebook api to get user data. Though facebook sends very minimal user data when user will visit your page app.
In this tutorial I’ll explain:
- How to add authentication feature in your page app using php sdk
- How to provide extended permissions list in the authorization page
- How to use graph api to get user’s data & update user’s status
- How to use FQL query
- How to parse signed_request sends by facebook
- How to detect if user liked your facebook page or not
Before proceeding:
UPDATE:
Facebook recently updated their PHP SDK to version 3.0 . This is a major update. So I updated this post and all codes based on SDK 3.0. This is a revised post with modified codes.
Recommended Reading
- iSimple – Graph API & IFrame Base Facebook Page Application Development
- PHP SDK 3.0 and Graph API base Facebook Connect Tutorial
1. How to add authentication feature in your page app using php sdk
Before proceeding first check out the flow chart of page app authentication we will use.
Now download the code, extract the zip folder and upload all the files in your application directory. There are total 9 files.
- index.php – is the main file that will load when user click the the tab application
- config.php – is the configuration file. Application settings should be written here
- facebook.php, base_facebook.php and fb_ca_chain_bundle.crt – are the php sdk 3.0 library provided by facebook
- fbmain.php - this is the file where I written the authorization logic. This file includes config.php and facebook.php so you only need to include this file in index.php
- ajax.php - is a backend php file that call facebook api to update user’s facebook status
- template.php, home.php, other.php - contains html/css/javascript code to render output to user. Where template.php is the main file within it home.php or other.php will load
This time I’ll only describe the parts of code, so download the code base and check yourself.
In fbmain.php
Loading php sdk library and configuration.
include_once "config.php";
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
Create facebook object, get user id, generate login and logout url. If a user is already logged in facebook and authorized your app, then $user will contain the user’s UID.
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
'redirect_uri' => $fbconfig['appPageUrl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
If $user is null or empty that means, user is not logged in facebook or not authorized your application.
//redirect user to login page if user is not logged in facebook and not authorized your application
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
If user approves the application from the authorization page the code will redirect user to the page app .
Please remember facebook did a major change here, previously we can provide cancel_url during generating of login url, but this is now not possible in PHP SDK 3.0. So whether user allow or not allow SDK 3.0 will redirect user to the url that we pointed. In this case it would be the page app url, so here a redirection will occur again to prompt user to allow the app (until user doesn’t allow).
To solve this problem, use below code and comment the redirection part, so in this case user will see a link that he has to allow this app. When he will click he will be redirected to the authorization page.
if (!$user) {
echo "<a href='{$loginUrl}' target='_top'>Allow Access This App</a>";
exit;
}
//redirect user to login page if user is not logged in facebook and not authorized your application
/*
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
*/
2. How to provide extended permissions list in the authorization page
In the login url generation link you’ll see there is a parameter named ‘scope‘, so provide the extended permissions here. Previously it was named “req_perms”
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
'redirect_uri' => $fbconfig['appPageUrl'],
)
);
3. How to use graph api to get user’s data & update user’s status
In index.php line number 7 you’ll see graph api is called. This time I called graph api to get user’s data and save them in $userInfo variable.
$userInfo = $facebook->api("/$user");
In home.php line number 36 you’ll I output this variable
if (isset($userInfo)){
d($userInfo);
}
Where d() is a function defined in fbmain.php
function d($d) {
echo '<pre>';
print_r($d);
echo '</pre>';
}
In ajax.php you’ll see I again called graph api to update user’s status
try {
$status = htmlentities($_REQUEST['status'], ENT_QUOTES) . " Checkout the tutorial: http://wp.me/pr3EW-zh";
$statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> $status, 'cb' => ''));
} catch (FacebookApiException $e) {
d($e);
}
4. How to use FQL query
Using fql query you can write some complex query to get users data. In index.php line number 9-15 you’ll see a basic fql query and the way to call fql query. You’ve to call the REST api for this.
$fql = "select name, hometown_location, sex, pic_square from user where uid=" . $user;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
In home.php line number 43 you’ll see I output the fql result
d($fqlResult);
5. How to parse signed_request sends by facebook
When a user clicks the tab application facebook sends an encoded signed_request parameter in your callback url. You have to decode this parameter using your application’s secret key. By parsing this parameter you’ll get some minimal basic data of user. Keep in mind that if you don’t need to call graph api, you can skip in this tutorial’s authentication part in your project and only use below function to parse the signed_request parameter. To parsing this, user doesn’t need to authorized your application.
In fbmain.php you’ll see
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
This method is defined by facebook. In index.php line number 23 you’ll see how I decoded the encoded parameter data
//This is the signed_request decoded data
$decodedSignedRequest = parse_signed_request($_REQUEST['signed_request'], $fbconfig['secret']);
And in home.php line number 103 I show the decoding data
d($decodedSignedRequest);
6. How to detect if user liked your facebook page or not
After parsing the signed_request data just check
<?php
if ($decodedSignedRequest['page']['liked'] == 1){
echo "User like this page";
}
else{
echo "No, User doesn't like this page";
}
?>
Additionally, you can include Facebook Javascript SDK and you can do some tasks via javascript API. To understand how to use javascript SDK please follow this tutorial.
So I think now you have a solid knowledge about how to use advance feature to develop facebook page application. Hope this tutorial will help you.












Hi,
I am a fan of your tutorial.
I am creating a iframe based application.
Please tell me how to share (text and image) automatically without showing the dialog prompt.
When i used ‘/me/feed’ post method, only text was sent.
I am breaking my head in this issue for last 1 month.
Thanks in advance for your help.
Use this code.
try { $wallpostpage = $facebook->api('/me/feed', 'post', array( 'message' => 'I like iThinkdiff.net', 'picture' => 'http://thinkdiff.net/ithinkdiff.png', 'link' => 'http://ithinkdiff.net', 'name' => 'iThinkdiff.net', 'cb' => '' ) ); } catch (FacebookApiException $e) { print_r($o); }Thanks Sir. But, it does not work.
I am calling the share function from a javascript function.
i am using giving my sample share optioncode (with comes with prompt popup box)
function goShare()
{
FB.ui({
method: ‘stream.publish’,
name: ‘xxxx’,
display: ‘dialog’,
link: ‘http://apps.facebook.com/xxxxx/’,
action_links: [{ text: 'Code', href: 'http://www.facebook.com/apps/application.php?id=xxxxx' }],
picture: ‘http://www.toonpool.com/user/36/files/tiger_293445.jpg’,
caption: ‘Come and Join xxxxxx’,
description: ‘hi’
});
}
How can I modify it so it works without popup or can you mention share code using javascript.
Sorry to disturb you again.
Visit http://www.facebook.com/thinkdiff.net?sk=app_113700398662301 and click status update tab. Now write something and click Update status via Ajax and PHP API. Now see what happens, if it works then just update ajax.php in my source code with the code that I given you earlier. If you smart enough, then it will solve your problem. Thanks.
Works great. Thanks Sir.
However, after it was posted, it displays an error “: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in ……..” in the Wall.
Can I know, how to remove the error?
hello sir ,
i am fan of ur facebook application.
i have to create facebook application to aceess facebook userdata and store in my backend …but it required json to install on server my server is old one…so instead of using json can i use XML…i tried lot but not able to get…
plz help me …
thanks in advance
can you send example of what you are doing? are you trying to parse json on server side?
Hi,
I’ve downloaded your script, and it al works, except for the Signed Request. I would like to know if the user likes my page, but is not working for me.
I’ve only changed the config file with my app id’s.
What could be the problem?
Regards,
Rory
Did you updated the config with proper secret key? Because decoding signed_request you’ve to parse the signed_request with application secret key.
I did notice that already, and I checked that several times.
UID and country are empty as wel. Like says NO.
Could it be that only approved apps can do a signed request?
I think that I’ve found out what the problem is. It only works in a Tab, not in an iframe app.
Do you have any solution for that?
checkout this tutorial http://thinkdiff.net/facebook/how-to-detect-fan-in-facebook-canvas-page/, but it is using old php sdk so using the concept and this api http://developers.facebook.com/docs/reference/rest/pages.isfan/ detect fan in canvas page.
You can parse the signed_request without requiring authorization, but it only returns a subset of the data if the user hasn’t authorized the app. This is mentioned on this page http://developers.facebook.com/docs/authentication/signed_request/, but it’s not super clear.
Specifically, you won’t get the user_id, expires, issued_at, or auth_token fields without authorization.
Once the user has authorized the app, those fields will be included in the signed_request.
In my code I’m checking whether the the signed_request['user_id'] field is empty. If empty, I redirect to the authorization URL. This seems to work well.
Hope that helps!
Thanks for your information.
First tutorial that really worked for me, thank you for that
Thank’s for sharing. I would love to work with you on our next Facebook project.
Thank you! Finally something that works, and a full tutorial that doesnt just give you small bits and pieces!
You dont know how long i have been looking for this, and how many times i have wanted to throw myself out the window trying to develop for facebook
Thank you thank you thank you!
Let me know if you ever need help with for example web design and i will be happy to help!
Glad to know it helps you and thank you for your interest to help.
Thanks for all of the tutorials, very helpful.
I can’t get this to work on the iFrame tab and I think it is because the template.php has tags that FB won’t allow.
When I test yours and my own version the tab is just blank.
Interesting though that when logged in FB does not return the tab error I was expecting…
Thank you Mahmud for the tutorial. If I just want to detect fans vs non-fans, I’d only need to use the signed_request…correct? That would be be steps 5 & 6 here.
No authorization needed, just fan vs nonfan detection on iframe page tab. Would I add the different content in step 6?
One user reported me, if you don’t authenticate you can’t parse signed_request to track whether user is fan or not. In that case you’ll get some minimal information.
thanks for the tutorial!
i tried it in an application tab but i don’t get the user details
using :
$fbme = $facebook->api(‘/me’);
$fbml['first_name'];
can someone help?
thanks
Try
$fbme['first_name'] not $fbml.
Excellent tutorial, thank you so much Mahmud!
Keep em coming
Thanks for the tutorial. It helped a great deal. I did run into one problem. I set the redirect as the Fan page tab that the app is on but it would only go to the main fan page. The only way I could get this to work was redirect to a page with a meta redirect to the tab. Kinda lame with 2 redirects but it works. Anyone able to do something like this with the one redirect in the tutorial?
Your tutorials are some of the best organized and thorough resources anywhere on the internet.
Trying to access app enters into endless loop redirecting from canvass to page to canvass. I am not a *real* programmer – I have taught myself the little I know.
I believe I am having an issue with getting session. Any obvious things come to mind for me to check?
Again – wonderful tutorials. You are a gifted teacher.
You could try to test the code in different hosting. I’m not sure why this redirection is happening in your case. Also upgrade your facebook page to the latest page format and also carefully check your application setting if everything is set correctly or not.
I was able to successfully install the demo and though I would share the results in order to help other who might be experiencing similar infinite loop issues. Installing on a separate host went off without a hitch. The problem I had previously must have bee related to the fact that I was installing to a WordPress based site which was using redirect rules. Please comment as to whether this would cause the infinite loop issues and if so, how might I go about resolving. The WordPress site has the files in a subdirectory (i.e. http://domain.com/cms/) but allows for access directly from http://domain.com via url rewrite.
Excellent tutorial
To the point en up todate.
Thank you so much!
Thanks very much, Very helpful.
I am facing a problem, My iFrame based app re-sizes itself as per the required height. But when the page gets longer, the share dialog box displayed at the middle (vertically) of the page, i.e., if you are at the top or bottom of the page, you wont see it, you rather have to scroll up or down. I have tried a lot of things and am frustrated.
Can you please help? You can see my app here at: http://apps.facebook.com/blogtop/ .
Regards
Sourav
Hi Sourav Ray,
I have the same problem. Have you already found a solution?
I also use the resize function, and I believe that that is the problem.
Normally they center the box at the middle of the screen, but the resize function sets the screenheight to the 5000px or whatever you size you want and places the box at 2500px from the top.
I tried the app by just changing the config, but after authorization instead of redirecting to the app, it gets redirect to the pageURL instead of to the app. Any ideas why?
Oh after I add the app to my page, it goes to infinite loop.
On further testing, it looks like it always goes to
if (!$session) {
echo “top.location.href = ‘$loginUrl’;”;
exit;
}
Thanks Neena for pointing out. It was an IE7 specific FB bug. Fixed now, courtesy, http://stackoverflow.com/questions/2955012/facebook-javascript-sdk-fb-xd-fragment .
Can you please look into the share dialog positioning issue?
That will be great help.
Sourav
I’ve used a CSS hack that opens the share-dialog box at the top and takes the user there. But this should not be the solution. The popup should open up near the share link always. And that’s the problem with my app, since the page becomes very long most of the times and if the share popup opens up in the middle of the page, my visitors can’t see that, rather they have to scroll up or down to see the popup.
**This is a iFrame based FB app using Graph API.
Sourav
I’m not sure where you fixed it but I downloaded the package again but still the same result. I also dont think it’s IE7 specific because I’m on Firefox. I’m not sure if it’s server specific or PHP specific or not but I tested on both Centos5 and Windows and got the same result.
The app is at http://apps.facebook.com/wisetargettesttwo/ and if you are interested, i can send you the config file and see if it has anything to do with the config.
Thanks for taking out the time to do this tutorial!
Oh since I dont see the app yet, I cant test anything else, but I’d love to help you with that.
I dont think I’m in luck with PHP SDK, I changed a few things and not using the PHP SDK and I think I can get the same result. Would kill to know why O_o.
One more question, when checking the like, we are checking the ‘Like’ of which page? App page or what?
Hi,
.
Thanks, it is working great
I have one issue – when I invite someone to use the app, if he accepts the invitation he is moved to the app page and not to the page withh the tabbed app.
any ideas?
thanks
Hello, I cannot get the comments plugin working. I assume I should change “aiwsh” in xid=”aiwsh” for the application ID and that’s all. That’s right? I only get a blank space… Thank you in advance!
It’s working ok now. Thank’s a lot!
First of all: thank you for the great tutorial!
I’m just wondering why do you created your own functions parse_signed_request() and base64_url_decode()? The corresponding methods are already there in PHP-SDK and you just need to run $facebook->getSignedRequest() to get that table with decoded signed request
Is it possible to invite someone to my page and get that user’s id without requiring them to install my app?
Hi,
I need some help to customize “like” button functionality on an image.
Here is a referece URL where you can see practical example.
http://www.facebook.com/FanPageEngine
When user press “Like FanpageEngine” button the functionality of like is done and the image is changed to “Continue” button.
Can you give me such type of customization.
Thanks
Amir
Hi,
I need some help to customize “like” button functionality on an image.
Here is a referece URL where you can see practical example.
http://www.facebook.com/FanPageEngine
When user press “Like FanpageEngine” button the functionality of like is done and the image is changed to “Continue” button.
Can you give me such type of customization.
Thanks
Amir
Anyone got ideas how to use Graph API to make own custom build multi friend input? I need just a simple textfield with autocomplete for selecting friends (and catch their ID). I have seen jquery based versions about multi friend selector but not multi friend input.
Hello Mahmud,
Thanks for your tutorials !
Just a question : is it possible to post on the wall of a friend ? Api allows that ? And so how does it work ?
Thank you.
Hello everybody,
I found this way if anyone is interested.
http://stackoverflow.com/questions/4983620/facebook-post-to-friends-wall-but-not-to-their-feed-graph-api
Peace N love
Zen
Hello Mahmud,
Thanks for the great tutorial,
When I try to run it by my self it get’s into an infinite loop,
where the page calls the application again:
It seems to me that I have a wrong parameter in :
$fbconfig['pageUrl']
Did any one faced the same problem?
Thanks you.
I had a similar problems. It was fixed when I changed the application URLs. in “Canvas” section I set http://apps.facebook.com/MYAPP and as “Tab URL” I set http://apps.facebook.com/MYAPP/index.php
Previously I had in Tab URL another folder like http://apps.facebook.com/MYAPP/MYTABFOLDER and I had this annoying infinite loop…
remember the trailing / in:
$fbconfig['appBaseUrl'] = “”; //”http://apps.facebook.com/xxxxxxxxx/”;
Second thought regarding the infinite loop,
the:
$fbconfig['appPageUrl'] Parameter, that Im using is different then in the example;
the example has a readable name:
http://www.facebook.com/thinkdiff.net
Where I am using something like:
http://www.facebook.com/pages/My-Tutl/12345678
Can this be the problem?
Thanks in advance,
Dan
No I think this is not the problem. Because infinite loop problem also happens sometimes in facebook connect base application also. But I don’t know the actual reason behind it, you may try to change your hosting. Because for my applications I never found such infinite problem.
Hi Dan,
Place this at the top of the page before any other code:
header(‘Content-Type: text/html; charset=utf-8′);
header(‘P3P:CP=”IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT”‘);
It worked for me. It is a IE cookie problem. IE doesn’t allow you to set a cookie from an iframe. Your page should already work fine outside the iframe and with other browsers.
I found the problem:
There is a need to add the security file of the php sdk.
I would like to thank to everyone who have helped me.
Dan
Can you please be more specific, I have the same problem, I have a loop in IE7 and I alredy tried putting this to no avail:
header(‘Content-Type: text/html; charset=utf-8′);
header(‘P3P:CP=”IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT”‘);
what security file are you talking about?
Regards
I have a problem with the property text.
The share stream shows just “propertiestext” not the variable I gave it. All the others work just fine.
How can I force it to use the variable?
function publishdata(propertiestext, etc..) {
var atch = {
name: titel,
href: titellink,
caption: caption,
description: (description),
media: [{ type: mediatype, src: mediasrc, href: medialink}],
properties: {
propertiestext : {text: propertieslinktext, href: propertieslink}
}
hi, i tried everything here and your other posts i finally add my app thanks to your tutorials but I could not make automatically update status, post to wall and share with friends, i have no understanding of coding . could you please but please help me with this. what i am trying to do is after each time user uses my application i want to appear on his wall either thru status update or wall post or both if i could.
please help
thank you
Hi!
I created a facebook app using your tutorial, however the AJAX is not working.. Even in your facebook app, the Update Status via AJAX and PHP API is not working. Pls help on how to make this work!
Looking forward for your response asap.
Thank you!:)
hi i try to add mysql code but all return sql error.
how to add sql code into this script.
thanks
great tutorial thanks again,
does anyone know how could i post to users wall without the publish promt with an image?
i would like to do autopublish but i could not find it anywhere yet
thank you
Hello,
Do you try ?
$result = $facebook->api(
‘/me/feed/’,
‘post’,
array(‘access_token’ => $this->access_token, ‘message’ => ‘my message..’)
);
Permission needed: publish_stream
Enjoy
Zen
thank you very much for your reply where do i add that code here in this code?
thanks
}
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: ‘stream.publish’,
message: ”,
attachment: {
name: name,
caption: ”,
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function publishStream(){
streamPublish(“Stream Publish”, ‘Thinkdiff.net is AWESOME. I just learned how to develop Iframe+Jquery+Ajax base facebook application development. ‘, ‘Checkout the Tutorial’, ‘http://wp.me/pr3EW-sv’, “Demo Facebook Application Tutorial”);
}
function increaseIframeSize(w,h){
var obj = new Object;
obj.width=w;
obj.height=h;
FB.Canvas.setSize(obj);
}
Hi,
If you want use javascript, you can try this code :
function streamPublish(name, desc ){
var body = name + desc;
FB.api(‘/me/feed’, ‘post’, { message: body })
For more info:
http://developers.facebook.com/docs/reference/javascript/fb.api/
Good luck.
Thank you now almost everything is working
2 questions
when i use
var url = ‘http://apps. ……my_app/’;
on the wall it shows my path to where i have all these files from here but when I click it takes to my application, how can i make a nice title there?
second what can i use to a link next to
Like . Comment . connect to My app
thank you
I am sorry but as you can understand i have no experience, all i did was i added the codes from him at this tutorial
http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development/
would the final code look like this?
thank you
}
function streamPublish(name, desc, hrefTitle, hrefLink, ){
var body = name + desc;
FB.api(‘/me/feed’, ‘post’, { message: body })
method: ‘stream.publish’,
message: ”,
attachment: {
name: name,
caption: ”,
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function publishStream(){
streamPublish(“Stream Publish”, ‘Thinkdiff.net is AWESOME. I just learned how to develop Iframe+Jquery+Ajax base facebook application development. ‘, ‘Checkout the Tutorial’, ‘http://wp.me/pr3EW-sv’, “Demo Facebook Application Tutorial”);
}
function increaseIframeSize(w,h){
var obj = new Object;
obj.width=w;
obj.height=h;
FB.Canvas.setSize(obj);
}
I am facing one problem with using facebook api since 2 days..
I am adding/creating page to facebook from my application asp.net..
I am passing content to facebook to add thsoe to facebook page created in my facebook application.. now how can i get that page id of facebook?????
I have set all urls in my application in facebook but still it is not returning any page id created on facebook.
I am redirecting to URL.. add.php?api key=xxxxx&page
and that page asks for selecting application and then page is created but i need page id which is created there in facebook return back to my application…..
How can i get page id???
Please help..
i try to make publish function like this, butit wont working. it wont sow title and image, really need help. thanks
function fb_publish() {
FB.ui({
method: “stream.publish”,
display: “iframe”,
user_message_prompt: “Publish This!”,
message: “Add personal message”,
attachment: {
name: “”,
caption: “Joe has tested his skills and did extremely well”,
description: “Here is a list of Joe’s skills:”,
href: “http://example.com/”,
media:[{
type:"flash",
swfsrc:"",
imgsrc:"",
"href":"http://example.com/"
}],
properties:{
“1)”:{“text”:”Reading”,”href”:”http://example.com/skill.php?reading”},
“2)”:{“text”:”Math”,”href”:”http://example.com/skill.php?math”},
“3)”:{“text”:”Farmville”,”href”:”http://example.com/skill.php?farmville”}
}
},
action_links: [{ text: 'Test yourself', href: 'http://example.com/test.php' }]
},
function(response) {
if (response && response.post_id) {
//alert(‘Post was published.’);
} else {
//alert(‘Post was not published.’);
}
}
);
}
name: “”,
swfsrc:”",
imgsrc:”",
this is the problem without / inside question mark
swfsrc:”",
imgsrc:”",
hah sorry lol i wrongly paste the code
I am using this as the basis to create an Application for my Nightclub.
I am working on an electronic guest list tab and it seems to be going ok. What I wan to happen is that when someone clicks on the event guest list it publishes an update to their profile and adds them to a list. This is all working so far.
I then want the doorman to be able to scroll through the list and find peoples names and next to their names is a “Check In” button and once they arrive they are then checked in to the club online.
I cannot seem to get this part working. I can check myself in no problem using the following code -
if (isset($_REQUEST['checkin_user'])) {
try {
$user = htmlentities($_REQUEST['checkin_user'], ENT_QUOTES);
$checkin_userUpdate = $facebook->api(‘/me/checkins’, ‘post’,
array(
‘place’ => ‘******’,
‘message’ =>’I just checked into ****** Nightclub after using their electronic guest list. Why dont you check it out!’,
‘coordinates’ => array(
‘latitude’ => ‘*****’,
‘longitude’ => ‘*****’,
)
)
);
} catch (FacebookApiException $e) {
d($e);
}
echo “User Checked In Successfull. “;
exit;
}
How could I modify this code to check in users that have given me permission??
Thanks
Im also facing the same problem with events. Did you got this to work?
hi
how to create account in facebook using php
1.or using curl
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: ‘stream.publish’,
message: ”,
attachment: {
name: name,
caption: ”,
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function publishStream(){
streamPublish(“Stream Publish”,
‘Thinkdiff.net is AWESOME. I just learned how to develop Iframe+Jquery+Ajax base facebook application development. ‘, <– how to get item from mysql
'Checkout the Tutorial', <– how to get description from php , example $desc
'http://wp.me/pr3EW-sv', <– how to get description from php , example $appurl
"Demo Facebook Application Tutorial" <– how to get description from php , example $caption
and how to attach image
);
}
Just started developing Facebook pages/apps with iframes. While this tutorial did wonders, do you have any ideas or examples for how to submit a simple contact form inside one of these? I’ve placed my form and it’s input fields in the “home.php” file, directed the form action to the processing script on my Web server and even used the target “_top”—but no submit action happens. Thanks in advance!
Nevermind! Scanned my code over (again) and didn’t even realize that my submit was outside my form! If all else fails people, double-triple-check your syntax and structure!
Many thanks for your apps Mahmud! Great job! I use iadvance app with fb:comments in tab, but recently i get unexpected trouble. Maybe you guys could help me. I launched a fan page and get over 500 fans within a day, people left many comments. But I decided to move to another hosting and, i made a mirror, changed ip, deleted app from tab while making changes. And after adding the app on host with a new ip again to page tab i have none of my comments found! they are all dissapeared and commenting started from the very begining. I changed only ip, domain name was the same! Could you please advice me is there any way to get comments back, or they are lost? And why was it happen?
Mahmud, you are Facebook Superman. Amazing tutorial. Can you explaine, how zappos fan page embed a poll with auto publish stream on their Landing tab? Thank you.
Hi guys,
when my app is added to Custom Tab I am facing to a problem with publishing in Safari (Unsafe Javascript error) all other browsers are OK .. any workaround?
when I access it directly everything is ok!
tnx
Hi Mahmud,
I am using your code – Thanks You!
However I have a problem: My application have number of stage:
1. Page for Non Fans/ Fans with go to application button
2. Facebook connect (using your fbmain.php file
3. The application which is game1.html file
The problem is when a new user start the application, after stage 2 the game1.html file is opened as a tab, but if the same user start again from stage 1 (and not go through the permission again), then the html file is opened in full window.
Any idea why?
Ilan
Hi Mahmud – great tutorial- i’ve followed everything above but i have a problem with something! – i see that in your example on your FB page, the iframe is loaded butj you never navigate away inside your iframe.
I’m loading a mini site into a FB page tab using the iframe method. I have a session when i land on my index.php but when i start moving around my mini site, the session is lost? – is there any way i can maintain my session – i’ve read somewhere that i coould append the serialised session to my links – ie <a href="link.php?”>?
Emm I don’t know about session passing with links. And for navigate I use ajax in side iframe.
Thanks for getting back Mahmud! – I would HUGELY appreciate help on this problem! – i understand that this is how you do it and it works SOO god i love it! But wouldn’t it be quite common for a mini site to be located in an iframe application? and hence with a mini site you’re going to have page reloads with the iframe? I’m SOOO close! – but i just need to understand things better so that the session that i initially have in auth.connect.inc (or your fb main.php) is kept as i navigate my mini site within the app frame?
Hi Mahmud, it would be soooooo good to find this out? – would this not be a common issue? -scenario is: you ahve a mini wordpress site as an FB application using the iframe method. You load the WP site, using the PHP SDK, you load the session etc, then you navigate (page reolad with-in the iframe obviously) the mini site, session disappears? It would be SOOO could to come up with a solution to this. The Javascript SDK always works – its just you need to do some things server side.
I’ve just included some of my source readings if you wanted to take a look?
http://stackoverflow.com/questions/4849373/using-facebook-graph-api-i-can-access-the-jsod-for-my-album-but-not-through-an-ap
http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/
http://forum.developers.facebook.net/viewtopic.php?id=59528
If i get it working i’ll post here!
Hi Mahmud
First of all, thank you so much for all your tutorials, I has been saving me a lot of time.
I have two questions with which I hope you can help me.
1) Is there any way for the authentication not to happen in a new page, but maybe in the iframe or in a popup. My iframe has multiple tabs, and would like it to go to a certain tab when auth is allowed, instead of reloading index again.
2) The first time the user allows my app permissions, it seems to take a while before it comes through. What happens now is that my page goes into a loop, because session is empty, and when it gets to auth process, it sees that its already allowed, and then loops again and again.
I hope this makes sense, but if not, let me know and I will try and explain some more.
Thanks
I would LOVEEEEEEEEEEEEE if this were to be demonstrated! – i agree – its not as nice a way as previously with FBML – its like we had more control before with the popup texhnique?
great tutorials that you have here, I need a favor, could you recommend a good book to learn how to develop applications for facebook that includes iframes, FQL and more?
Thanks
Mahmud-
Great tutorial!
I just want to confirm something. After much research it looked like I could get basic information about the user (uid, fname, lname) and whether or not a user has liked a page without any special user authorization. Your tutorial implies that I cannot.
Can you help me out here? It would appear if anyone knows the answer it would be you.
Thanks!
Dave
Mahmud,
It great tutorial explaining the overview of the facebook application. I found an article which explains about creating application using powerful php framework yiiframework
http://www.makeurownrules.com/create-facebook-yiiframework-graphapi.html
I hope it would help everyone to get started with development of facebook application
Cheers,
kapil
Hello, great tutorial, thatnks a lot!. Sorry about this but I’m about to become crazy as I keep getting an error message for the streampublish function. Maybe there is something I’m doing wrong? Any help would be much appreciated:
http://www.facebook.com/pages/Lore-Ipsum/144965245569895?sk=app_212597042085314
Fixed. Thank you.
Great tutorial. I could development of my FB app started in no time. Thanks!
Hello Ahsan!
Thank you for your great ideas and source code
I have a big problem, I dont know how we can export to CSV file the facebook app users datas (name and email)
Can you help me pls?
Thanks!
Easy, just gather email and name write in your database and later create a .csv file and export it. If you search in google you’ll get lot of examples for php and .csv file example.
Hi,
Your site is a great resource, I have learned a lot.
I was wondering if you and the community could help me on my issue::
Is there a way of showing a list of my fan page liked pages? Is there an fql query to check for the pages that my fan page likes?
I found the option of this URL: http://www.facebook.com/browse/?type=favorite_pages&page_id=your page id]
which gives a list of your pages favorite pages, but I would like to write an application which will show a list consisting of the page’s name, logo, number of fans(and any other optional relevant info). A list which I can control design wise and show as an iframe application.
Thanks a lot in advance,
Dan
Hi Mahmud,
My application which works very like yous has suddenly stopped working today? – are you ahving the same difficulties? I’ve copied and pasted what its trying to do – it just goes into an infinite loop ..
(1) http://www.facebook.com/thinkdiff.net?sk=app_113700398662301
(2) http://www.facebook.com/connect/uiserver.php?
app_id=113700398662301&
next=http%3A%2F%2Fthinkdiff.net%2Fdemo%2Fnewfbconnect1%2Fiframe%2Fiadvance%2Fredirectpage.php&
display=page&
cancel_url=http%3A%2F%2Fthinkdiff.net%2Fdemo%2Fnewfbconnect1%2Fiframe%2Fiadvance%2Fredirectpage.php%3Ft%3D1&
locale=en_US&
perms=email%2Cpublish_stream%2Cstatus_update%2Cuser_birthday%2Cuser_location%2Cuser_work_history&
return_session=1&
session_version=3&
fbconnect=0&
canvas=1&
legacy_return=1&
method=permissions.request
(3) http://apps.facebook.com/thinkdiffdemo/iadvance/redirectpage.php?perms=email%2Cpublish_stream%2Cstatus_update%2Cuser_birthday%2Cuser_location%2Cuser_work_history&selected_profiles=100000856823869&installed=1&session={%22session_key%22%3A%222.ITyrc1YHBMCtJosBUqwuRA__.3600.1302782400.1-100000856823869%22%2C%22uid%22%3A%22100000856823869%22%2C%22expires%22%3A1302782400%2C%22secret%22%3A%22JTrCW8AFpyoF7g0nrgAzjg__%22%2C%22access_token%22%3A%22113700398662301|2.ITyrc1YHBMCtJosBUqwuRA__.3600.1302782400.1-100000856823869|gAo7j6XpyW0gqqwAFantHa6ZiEo%22%2C%22sig%22%3A%224f15a4cbf3f3200aeff8d807298e8315%22}
(4) http://www.facebook.com/thinkdiff.net?sk=app_113700398662301
Check if you used any query that needs special extended permission or not. If it needs extended permission, then provide the permissions at the first time. So that when you call the api it doesn’t redirect or make infinite loop.
I have same problem started today
any solutions please?
thank you
http://thinkdiff.net/facebook/facebook-apps-infinite-redirection-solution/ checkout this. This solution works for me.
You are a legend! thank you! – do you know what the exact problem was by any chance?
Thanks for getting back so quick mahmud – this is your application above? – its happening with mine also – which works like yours!
hi mate,
i am trying to show different content to non-fans and page fans, before it was very easy to do using staticFBML.. do you know some solution for iframe apps?
thanks!
Tony
Yep – see below ..
require_once ‘facebook.php’;
$facebook = new Facebook(array(
‘appId’ => $config['appid'],
‘secret’ => $config['appsecret'],
‘cookie’ => true
));
$signed_request = $facebook->getSignedRequest();
The signed_request is basically ..
Array (
[algorithm] => HMAC-SHA256
[expires] => 1302814800
[issued_at] => 1302808396
[oauth_token] => 187887607909189|2.qfGfz1iqMhbxsTb7o1jNmA__.3600.1302814800.0-710728134|7cj1T-th7wIv1G4qDasMlgryccM
[page] => Array (
[id] => blahblah
[liked] => 1
[admin] => 1
)
[user] => Array (
[country] => ie
[locale] => en_US
[age] => Array (
[min] => 21 )
)
[user_id] => blahblah
)
so you can access the liked part by going ..
$like_status = $signed_request["page"]["liked"];
Now you have everything …
if($like_status):
//show something to fans
else:
//show something to non fans
endif;
Thanks for your reply! but here I think user has to Add/install app first, right? because if app is not added you are not getting $signed_request[page][liked]…
Nah Tony – you always get the signed request when the application is loaded!
Yeah, but the problem is that I am getting signed_request, but I am not getting [page].. am I doing something wrong?
tnx
ah i see! – let me take a look! – wonder has it got something to do with your application settings when you were setting up? – ie have you filled out a canvas and tab URL?
This Tutorial literally saved my life!! I’m so thankful to you right now …
I’m so close to a project’s deadline and i couldn’t authorize my app because of the redirect issue ..
Thanks a million!!!
Hello, many thanks for this great post.
I don’t require authorization at the iFrame’s app first page but at the second, as I first present the promotion etc.. The problem is that with your example once authorised I get back to the home application page but I want to redirect to the second (in your example imagine that it’s other.php to be included into template.php). If I try to do it the page appears but not anymore inside the tab but at its full canvas without the left side Facebook’s menu etc… What can I do please? And thank you in advance.
Hi Juan – you ever solve this? – i had the same problem last week! – in the example in this post, Mahmud adds the script ‘index.php’ as the tab URL – so the the URL is http://apps.facebook.com/APPLICATION/index.php.
The options in facebook.com/developers look different – there is no prefix to the URL like ‘http://apps.facebook.com/APPLICATION/’ as it appears in this tutorial – therefore you can add any URL.
I’ve played around with putting in the full URL to my application – ie ‘http://www.myserver.com/application/iframe.php’ which works but i’m having problems with maintaining my session as i move around my iframe mini site!! Someone suggested to me to use relative links within my mini-site – ie http://apps.facebook.com/APPLICATION/iframe.php, http://apps.facebook.com/APPLICATION/aboutus.php, http://apps.facebook.com/APPLICATION/contactus.php etc – think this may solve my session problem – BUT – i have your problem with this method! – the canvas is pulled into the view – with the right hand side ads and the facebook blue header and everything! – i don’t see this in Mahmud’s example – i would really love to see how he done this because i’ve basically done the same as him and my app looks different!
Hi Richard,
I couldn’t find a reason why it is happening or how to avoid it. What I did was to include an if statemente asking: Has this user already given authorization? if so I load a different page. It seems to work so far until I find a more clean way of doing it…..
if($facebook->getUser()){
// Has already given authorization
}
i actually had an other application that i don’t touch to it and i checked that one and it has the same problem
it redirect or make infinite loop
can you please help
thank you
Great tutorial. Helped me to get through a rough patch. Especially the redirection thing (what a pain in the rear). Keep up the good work!
Thanks for your fast reply Ahsan! I finished the export modify successfully.
I add a new function to application, do status update automaticly (fbmain.php):
try {
if ($doStatusUpdate) {
$statusUpdate = $facebook->api(‘/me/feed’, ‘post’, $statusText);
}
} catch (FacebookApiException $e) {
d($e);
}
But when I go back to the application, the app is posting to my wall all time when I click the app tab. Any idea how can I modify this for only the first time posting to wall?
Thank you…
Hi Mahmud,
I have a general question for you on permissions – one of the guys in this forum actually asked this a while back but i haven’t seen a response!
Is there any nicer ways to get permissions from a user rather than redirecting them away and back when the load the application in the page?
With FBML, you had nice control with functions – ie require_login() and the permissions dialog. It seems the way now is a little less controlled? is there anyway to do this with a popup you reckon?
Thanks Mahmud
Hi Richard,
Unfortunately I don’t know, there might be someway, please checkout facebook documentation. For some months I’m not actually working in facebook base application development. Now I occasionally check their documentation so I might miss if there is any way.
No worries! – thanks i’ll experiment and post here if i find a solution!
Just seen this – Facebook talking about the graph API and permissions! – really good! – http://developers.facebook.com/videos/#graphapi
Hi guys,
is there any PHP example of adding multiple tags to image with posting to a friend’s profile?
thanks
Anyone?
Just seen this also – its a nice way to see what you can retrieve from the Graph API – https://www.simoncross.com/fb/graph/ – its called the Graph API explorer
hi,
i just noticed that if i use firefox, i can publish with my application but if i use IE it does not publish.
can you please help?
thank you
is that me only? is anyone has same problem?
thank you
Hi Mahmud:
The Facebook fql documention for page_fan implies that I can get the uid of a person that has liked my page without any special authorizations from the user. The fql page_fan documentation says: “Query this table to return information about the fan of a Facebook Page. You can query this table without an auth_token or a session key.”
I am using the following code but only get a null array for the result:
$data = $facebook->api( array( ‘method’ => ‘fql.query’, ‘query’ =>
‘SELECT uid FROM page_fan WHERE page_id=”page_id” and uid=”‘.$me['id'].’”‘ ) );
print_r($data);
//if the user is fan, uid will be returned, otherwise, an empty array.
I tested this with a user that I know has liked the page.
Any suggestions?
Thanks Mahmud,
Dave
Hey Ahsan
I really love this platform and Thanks for sharing your Knowledge which lot of people don’t do.
These days i am struggling with a problem and unable to find a solution and i hope may be you can guide me on that.
I am posting on a fan page of web project using cron job. i am able to get the offline access and than posting on wall of page. Problem I have is, I want to post as an admin not as a user. do you have any advise ?
Below is the code
$post = array(
‘access_token’ => ‘Offline token from db’,
‘message’ => ‘This message is to test offline access – ‘ . date(‘Y-m-d H:i:s’)
);
$res = $facebook->api(‘/165501263508998/feed’, ‘POST’, $post);
Hi!!
its nice to see a web like this it very helpful
i need argent help any one who this comment.
i have done exactly wat its said in article
now my facebook apps page is keep refreshing continuously
i tried so many things. but still its same…
even canvas page also
evgen if i make as page tab also its keep refreshing…
anyone have idea to solve this problem…?
thank you
hi Mahmud
Pretty gud stuff found here..
i want to post some thing on Facebook Page so how could i do that programmtically by not to asking any one…
Hi there Mahmud, we’ve been successfully using your previous iframe app demo for quite a while and have been experimenting with this version too with no problems….
This morning we received a load of emails from Facebook Developer Relations:
Dear Developer of XXXXXXXXX,
Our automated systems have detected that you may be inadvertently allowing authentication data to be passed to 3rd parties. Allowing user ids and access tokens to be passed to 3rd parties, even inadvertently, could allow these 3rd parties to access the data the user made available to your site. This violates our policies and undermines user trust in your site and Facebook Platform.
In every case that we have examined, this information is passed via the HTTP Referer Header by the user’s browser. This can happen when using our legacy authentication system and including , or content from 3rd parties in the page that receives authentication data from Facebook. Our legacy mechanism passes authentication information in the URL query string which, if handled incorrectly, can be passed to 3rd parties by the browser. Our current OAuth 2.0 authentication system, released over a year ago, passes this information in the URL fragment, which is not passed to 3rd parties by the browser.
Please ensure that you are not allowing this data to be passed immediately. Accessing your site as a test user while running a HTTP proxy/monitor like Charles or Fiddler is the best way to determine if you are allowing this information to be passed. If you discover the issue, you can do one of two things:
1. Migrate your site to use our OAuth 2.0 authentication system. We are requiring all apps and sites to update to this mechanism by Sept. 1, 2011. Migrating now will address this issue and ensure that you are one of the first to meet the deadline. For more details, please see our Authentication Guide.
2. Create and use an interstitial page to remove the authentication data before redirecting to your page with 3rd party content. This approach is used by many of our largest developers today (although they are all migrating to OAuth 2.0 shortly). This is a simple and straightforwardchange that should have minimal impact on your site. For more details on this approach, see our Legacy Connect Auth doc.
Because of the importance of ensuring user trust and privacy, we are asking you to complete one of the above steps in the next 48 hours. If you fail to do so, your site may be subject to one of the enforcement actions outlined in our policies.
If you have any questions or believe you have received this message in error, please contact us.
Facebook Developer Relations
We have a lot of clients that we have created apps for based on your set up code is it is the best code out there that we could find. Facebook documentation is, as you know, not the best. So,now, seems like we have a major problem and FB have given us 48 hours to ressolve. From what I can understand your methods are using what they call “Legacy” and we have to update to Auth2.0 in the next 48hrs (Despite deadline for new apps being Auth2.0 not being until 1st Sept)
Have tried to read up on this Auth2.0 and am even more confused by it all now.
Facebook provide a demo run with friends app, apparently with Auth2.0 but it is written in Python! Useless to me (an a lot of other devs) who are working in PHP.
Many thanks for all you have done for the FB Dev community and any help/advice you may be able to share on this greatly appreciated.
Regards Tony
http://developers.facebook.com/docs/authentication/
Hi Anton, am well aware of Facebook docs thank you. The reason many of us prefer working examples like the ones Mahmud provides is their simplicity to follow and his step by step explanations, so, how do we combine the working examples from here with the Auth2.0 login example from FB docs wiki? Any full working app samples in PHP that abide by FB latest T&C’s for Auth2.0. Sample app provided by FB with Auth login is written in Python). Am thinking many devs are going to be facing this issue in the coming months; quote FB “Migrating now will address this issue and ensure that you are one of the first to meet the deadline”
mate, did you try to open that page? there’s everything there including PHP example
Hi guys, am trying this sample but getting something wrong somewhere. Fb keeps returning error Fatal error: Function name must be a string in /home/content/69/3438869/html/XXXX/XXXXX/auth2.0/test.php on line 7 which relates to $session_start(); in the php so must be something wrong in lines 1-6
app id is ok for sure, as too is secret so must be doing something wrong in $my_url – any ideas, obviously some stupid little mistake I’m making somewhere but cant see it
$app_id = ‘XXXX’;
$app_secret = ‘XXXX’;
$my_url = ‘http://www.myservercom/myfolder/myfolder/’;
remove $ sign from $session_start();
Hi Tony, many thanks for your help on this, Typical that FB docs in core concepts even has code that is incorrect.
Have removed the $ as suggested and that now takes us through to app login which is progress
Downside its now returning “The state does not match. You may be a victim of CSRF”
http://www.facebook.com/pages/DRG-Auth20/202928289748318?sk=app_162483307148878
guess this the security FB want us to tighten up on with our apps, but am unsure what it is thats still not quite right. Could it have anything to do with SSL and https?
Thanks for your help – regards Tony
So, after wasting all morning on this with Facebook giving us 48hours to update our apps to Auth2.0 instead of Legacy, thought I’d try to save any others facing this problem some hassles.
Seems the good old boys at FB that have posted their Core Concepts code have not 1 but 2 mistakes in it – no wonder people prefer tutorials from the likes of Mahumud.
Anyway, code from FB Reads:
<?php
$app_id = 'XXXXXX';
$app_secret = 'XXXXXX';
$my_url = 'https://www.myserver/myfolder/myfile.php;
$session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state"
. $_SESSION['state'];
echo(" top.location.href=’” . $dialog_url . “‘”);
}
if($_REQUEST['state']== $_SESSION['state']) {
$token_url = “https://graph.facebook.com/oauth/access_token?”
. “client_id=” . $app_id . “&redirect_uri=” . urlencode($my_url)
. “&client_secret=” . $app_secret . “&code=” . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = “https://graph.facebook.com/me?access_token=”
. $params[‘access_token’];
$user = json_decode(file_get_contents($graph_url));
echo(“Hello ” . $user->name);
}
else {
echo(“The state does not match. You may be a victim of CSRF.”);
}
?>
As Tony correctly states above $ needs to be removed session_start();
There is also a second problem with this code from Facebook; &state should read &state=
Final code we got working is as follows:
<?php
$app_id = 'XXXXXX';
$app_secret = 'XXXXXX';
$my_url = 'https://www.myserver/myfolder/myfile.php;
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo(" top.location.href=’” . $dialog_url . “‘”);
}
if($_REQUEST['state']== $_SESSION['state']) {
$token_url = “https://graph.facebook.com/oauth/access_token?”
. “client_id=” . $app_id . “&redirect_uri=” . urlencode($my_url)
. “&client_secret=” . $app_secret . “&code=” . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = “https://graph.facebook.com/me?access_token=”
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo(“Hello ” . $user->name);
}
else {
echo(“The state does not match. You may be a victim of CSRF.”);
}
?>
Thanks Tony and Anton for your input on this and keep up the good work Mahmud
Regards Tony F
sometimes I think that they are leaving this mistakes intentionally.. just to make developers’ life more difficult
))
btw.. Tony and Anton is one person.. just from two different computers .. haha!
are you sure that you have $_SESSION['state'] generated and passed to auth url?
can i see your code?
wait.. i think if you change if($_REQUEST['state']== $_SESSION['state']) to something like if(isset($_REQUEST['state'])&&$_REQUEST['state']== $_SESSION['state'])
it will not show that message ..
or you can just comment it out
// echo(“The state does not match. You may be a victim of CSRF.”);
Hi Tony, I just editted Facebooks original code from :
$dialog_url = “http://www.facebook.com/dialog/oauth?client_id="
. $app_id . “&redirect_uri=” . urlencode($my_url) . “&state”
. $_SESSION['state'];
to:
$dialog_url = “http://www.facebook.com/dialog/oauth?client_id="
. $app_id . “&redirect_uri=” . urlencode($my_url) . “&state=”
. $_SESSION['state'];
ie changed “&state” to “&state=” and that seemd to ressolved the log in issues – following login now get the correct “Hello Tony F” greeting message so am assuming we are fully Auth2.0 compliant and 3rd party attacks cannot/should not be an issue.
Facebook should really do something to ensure their Wiki code is correct, especially in a core issue like this and them giving us a 48 hour deadline to ammend all of our apps – have emailed them to let them know
Regards Tony F
great, I didn’t notice that ..
I was thinking that $_REQUEST['state'] is not set for some reason when you load page first time .. anyway good to hear that you’ve managed to solve it
WOWOWOW
sorry if i have asked something stupid.
Great application works like a charm. Just one question
you are using
to show users country, how can i show users first name in similar way. May be very stupid question
Regards
Nik
hi Nik, you can try $fbme['first_name']
Wow that worked
One more question. I have customized this script a lot (for a non coder).
On the social plugin tab When users post comments i want ability for other users to “like” it like they have on wall posts. Is that possible or do i need to use some other method to do this?
Hopefully soon i will post link to my finished app here for your comments.
Regards
Nik
I don’t really understand what you mean.. if you mean Comments Box social plugin – it has Like button , check here http://developers.facebook.com/docs/reference/plugins/comments/
Hi sorry to bother you again if u visit http://www.facebook.com/thinkdiff.net?sk=app_113700398662301 and clock on social plugin. Please reffer screenshot http://www.picpaste.com/like-2f1SOpw1.png
I tried to replace your code code which i generated from the link you gave me. I got the “like” button on comments the way i wanted but then i lost ability to administer the posts
Regards
Nik
hi mate, did you read that plugin page properly?
…To moderate, you need to list yourself as an admin. To do this, simply include open graph meta tags on the URL specified as the href parameter of the plugin. Include:
To add multiple moderators, separate the uids by comma without spaces.
If your site has many comments boxes, we strongly recommend you specify a Facebook app id as the administrator (all administrators of the app will be able to moderate comments). Doing this enables a moderator interface on Facebook where comments from all plugins administered by your app id can be easily moderated together.
…
Humm okay now i am almost done everything even got rid of infinite redirection issue (missing trailing /) now one last question guys. Is there a way where users can attach their link in fb:comments like it does on wall? where fb pulls info from the link and thumbnail?
Regards
Nik
i getting this error please help Fatal error: Call to undefined function d() in …….
If undefined then define it.
function d($data){ echo '<pre>'; print_r($data); echo '</pre>'; }error says undefined, it means that function was not defined or file with the function was not included
fbmain.php code
$fbconfig['appid'],
‘secret’ => $fbconfig['secret'],
‘cookie’ => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
‘canvas’ => 1,
‘fbconnect’ => 0,
‘display’ => ‘page’,
‘next’ => $fbconfig['baseUrl'] . ‘/redirectpage.php’,
‘cancel_url’=> $fbconfig['baseUrl'] . ‘/redirectpage.php?t=1′,
‘req_perms’ => ‘email,publish_stream,status_update,user_birthday,user_location,user_work_history’
)
);
$fbme = null;
if (!$session) {
echo “top.location.href = ‘$loginUrl’;”;
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api(‘/me’);
} catch (FacebookApiException $e) {
echo “top.location.href = ‘$loginUrl’;”;
exit;
}
}
function d($d) {
echo ”;
print_r($d);
echo ”;
}
/**
* This function is used to decoding signed_request data
* more information is here http://developers.facebook.com/docs/authentication/signed_request
*/
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode(‘.’, $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== ‘HMAC-SHA256′) {
error_log(‘Unknown algorithm. Expected HMAC-SHA256′);
return null;
}
// check sig
$expected_sig = hash_hmac(‘sha256′, $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log(‘Bad Signed JSON signature!’);
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, ‘-_’, ‘+/’));
}
?>
index.php
‘fql.query’,
‘query’ => $fql,
‘callback’ => ”
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
//This is the signed_request decoded data
$decodedSignedRequest = parse_signed_request($_REQUEST['signed_request'], $fbconfig['secret']);
$_SESSION['login']['signed']=$decodedSignedRequest;
//set page to include default is home.php
$page = “home.php”;
include_once “template.php”;
?>
i have to acess facebook userdata after allow to acess user information…..and hv to use XML instead og JSON is it possible…?
plz help me
i resolved problem, thank you, now i need help with this:
i have this code to check if user liked my fan page
# Check whether user likes page
$likeID = $facebook->api(array(
‘method’ => ‘fql.query’,
‘query’ => ‘SELECT target_id FROM connection WHERE source_id = ‘ . $fbUID . ‘ AND target_id = ‘ . FB_PAGE_ID
));
it works fine, but i need call this function again on button click, because if doesn’t liked i show up like dialog, so when user click like and OK button dialog need to be closed, i hope u understand me.
Thanks
fbmain.php code
$fbconfig['appid'],
‘secret’ => $fbconfig['secret'],
‘cookie’ => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
‘canvas’ => 1,
‘fbconnect’ => 0,
‘display’ => ‘page’,
‘next’ => $fbconfig['baseUrl'] . ‘/redirectpage.php’,
‘cancel_url’=> $fbconfig['baseUrl'] . ‘/redirectpage.php?t=1′,
‘req_perms’ => ‘email,publish_stream,status_update,user_birthday,user_location,user_work_history’
)
);
$fbme = null;
if (!$session) {
echo “top.location.href = ‘$loginUrl’;”;
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api(‘/me’);
} catch (FacebookApiException $e) {
echo “top.location.href = ‘$loginUrl’;”;
exit;
}
}
function d($d) {
echo ”;
print_r($d);
echo ”;
}
/**
* This function is used to decoding signed_request data
* more information is here http://developers.facebook.com/docs/authentication/signed_request
*/
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode(‘.’, $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== ‘HMAC-SHA256′) {
error_log(‘Unknown algorithm. Expected HMAC-SHA256′);
return null;
}
// check sig
$expected_sig = hash_hmac(‘sha256′, $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log(‘Bad Signed JSON signature!’);
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, ‘-_’, ‘+/’));
}
?>
index.php
‘fql.query’,
‘query’ => $fql,
‘callback’ => ”
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
//This is the signed_request decoded data
$decodedSignedRequest = parse_signed_request($_REQUEST['signed_request'], $fbconfig['secret']);
$_SESSION['login']['signed']=$decodedSignedRequest;
//set page to include default is home.php
$page = “home.php”;
include_once “template.php”;
?>
i have to acess facebook userdata after allow to acess user information…..and hv to use XML instead og JSON is it possible…?
plz help me
http://developers.facebook.com/docs/authentication/signed_request/
…The signed_request parameter is the concatenation of a HMAC SHA-256 signature string, a period (.), and a base64url encoded JSON object…
this means that you can get JSON only, if you need/wish to work with XML you need to parse JSON first using json_decode or anything else
to work with JSON it’s not really necessary to have json_decode installed. you may find alternatives here:
http://json.org/
Thanks Tony for your added information.
it’s ok mate.. thank you for you blog
thanks for ur reply
i tried but not get…
i refer ur tutorial on iadvance….can u give me solution…so that….i can acess facebook userdata in my backend using xml instead of json….example..email_id,date of birth etc..
plz help me..
thanks in advance.
sanjay, did you read my answer? you need to parse JSON and after parsing you can convert it into whatever you need.. XML, array, string and etc..
how to parse JSON – http://json.org/
’117743971608120′,
‘secret’ => ’943716006e74d9b9283d4d5d8ab93204′,
));
$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) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api(‘/naitik’);
?>
php-sdk
body {
font-family: ‘Lucida Grande’, Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
php-sdk
<a href="”>Logout
Login using OAuth 2.0 handled by the PHP SDK:
<a href="”>Login with Facebook
PHP Session
You
<img src="https://graph.facebook.com//picture“>
Your User Object (/me)
You are not Connected.
Public profile of Naitik
i tried to run this code in wamp 2 but it doent display userdata…
plz help me
i realy oblised to ur tutorial and ur post
thanks
i am trying to run this code on local wamp 2..but it does not display $user is empty array
code is like this…would u plz help me
’117743971608120′,
‘secret’ => ’943716006e74d9b9283d4d5d8ab93204′,
));
$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) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api(‘/naitik’);
?>
php-sdk
body {
font-family: ‘Lucida Grande’, Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
php-sdk
<a href="”>Logout
Login using OAuth 2.0 handled by the PHP SDK:
<a href="”>Login with Facebook
PHP Session
You
<img src="https://graph.facebook.com//picture“>
Your User Object (/me)
You are not Connected.
Public profile of Naitik
thanks in advance
Hi sanjay
Posting your app secret in public forum is not a good idea
ohh nikhil it’s .not real it’s example
do u have any solution….?
well i might have i am trying to implement something similar will let you know how it works after weekend
hello,
i trying to retrieve userdata who click on my like button
but i am not able to get it …JSON not install on my server…i tried in XML….but parsing problem i refer to http://json.org/ but not able to get how decode signed_request……
plz help me….
thanks in advance
hello @vaishali,
u need to parse json first for this u can use http://gggeek.altervista.org/sw/article_20061113.html
here u can see json_decode & Mxlrpc….and u can easily decode ur signed_request..then check if signed_request
then like else
“msg”
decode in regular way and parse using one method listed on json.org
How do I know when a user clicks a Like button?
everything was working just fine before but now this happens
what does this mean
Fatal error: Uncaught OAuthException: (#200) Feed story publishing is disabled for this application. thrown in /data/17/1/89/73/xx/user/xxx/htdocs/xxx/sohbet/facebook.php on line 560
what can i do?
thank you
hi, I think everything is written in the error…
story publishing is disabled. seems it has been disabled for spam or negative feedback
yes but how come application is not displaying
now what? how can i fix it?
thank you
You need to redirect to authentication page if the session isn’t set.
how would i redirect to authentication page if the session isn’t set
thanks
disable pulishing in your app
I Think you have problem with logout and login again,
when you logout,at that time access token will change.
the cookie is used to store the access token. By
calling Facebook user session it will check again if there are cookies that store the access token, if it does it wll get from cookie.
I think you have to clear cookie first and try again.
how can i add image to below when shared
thank you
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: ‘stream.publish’,
message: ”,
attachment: {
name: name,
caption: ”,
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function publishStream(){
streamPublish(“Stream Publish”, ‘Thinkdiff.net is again awesome. I just learned how to develop Iframe base facebook page application development. ‘, ‘Checkout the Tutorial’, ‘http://thinkdiff.net’, “Demo Facebook Application Tutorial”);
Hi, is this tutorial still updated? I thought, that Facebook API changed (PHP SDK 3), but this example still works.
I think you can check these SDK3 tutorials:
http://thinkdiff.net/facebook-connect/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development-php-sdk-3-0/
I am using your iAdvance Facebook. When I navigate to my application it correctly ask me for the authentication (as in your app). After my approval it doesn’t find the app page.
What I am doing wrong?
Thanka
now it finds correctly the facebook page with my app, but there is another problem: if I navigate directly to http://www.mysite/ApplicationFolder/ it runs my app but it is outside Facebook. I expected to see the page the same way, I see in facebook, with the FB graphic interface.
Any help.
Thanks
Hello stefano maida,
i faced same problem & finally solved.
instead of using address of your application url on server
use facebook canvas application name that u have given in facebook
application. for example i have used
http://apps.facebook.com/renation/ here renation is my canvas application name
i hop you get your answer
Thanks sanjay for Your reply. It solved my problem!!!
Thanks so much
Stefano
Hello,
I have create an apps using your tutorial But I faced two problem
1. when other user visiting the apps they see this massage.
(An error occurred with herbcare. Please try again later.)
Here is my apps link: https://apps.facebook.com/herbacare/
and: https://apps.facebook.com/viviona/
2. second problem is when you see this apps you see the height is too small and scrolling the apps.
Please solve this . How to increase height and what about the error problem?
Regards,
Salayhin
I will not check your link, this tutorial is for page application not for facebook site application. Please see specific tutorial to solve your problem. Please checkout this tutorial http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development-php-sdk-3-0/
Hi Mahmud, great post and great work, but I’m having some problems.
After setting up all the data and setting an iframe tab and authorizing the app I stacked in an infinite redirect loop. after poking around the code I’ve found out that I’m allways get to “if (!$user) {” (fbmain.php line 44).
I’ve checked a little more and $user = $facebook->getUser(); always returns 0.
I don’t know what am I doing wrong, only thought is about “appPageUrl” which I don’t know from where to extract.
Would love some help regarding.
Thanks
Well, After fighting this a lot of time, apparently it is hosting problem. I’ve moved my app from dreamhost to other hosting and like magic – my problem was solved.
Any Idea why?
emm no I don’t know what’s the reason. May be PHP extension problem not sure.
Hi mahmud.
Thanks god I’ve found this post.
Do you know how to make my fb tab iframe app to redirect user back to facebook in case user gets the iframe url and opens it in another tab, separately/directly ?
Thanks
No I don’t know, you may have to research about it.
Hi mahmud,
i am getting page id in my facebook page tab application using $_REQUEST['signed_request']) .
but due to security CURL is not enabled in one of my servers. so i thought of doing it in
javascript. how can i get my ‘signed_request’ in java script. please reply to me
thanks in advance.
Woah this weblog is wonderful i like studying your articles. Keep up the great work! You recognize, a lot of individuals are looking round for this info, you can help them greatly.
is user dp setting possible through application. Is this available in graph api?
Hello sir i have found a flaw in your tutorial. When app reaches after the permission then onclicking on like button the page does not refresh. Please find the solution.
Here is a link that best describes the problem http://facebook.stackoverflow.com/questions/7289711/like-button-on-fan-page-does-nothing-after-permissions-redirect
Anticipating quick solution as far as possible.
Issue :
1. Like your application demo , i am getting screens
- Allow access.
when i allow access of information.. it is redirecting to http://www.facebook.com/“app name”?sk=app_appid but when it comes here, page is continually redirecting on the same page with state/code etc.. in url.
but when i click on “gotoapp” button on right hand side then click the same url then i can get info of user… Please any body can help me…
Hello sir can you help me?
I want to know how to create an app like this:
http://on.fb.me/yZUF0G
Please i really need this.
Hi mahmud,
I want to get user’s work history. I am able to find it in javascript using FQL queries. But unable to parse that object and get organization name.
How to do that. Please advice.
Thanks
Pankaj
hello Mr.mahmud ahsan
i don’t know how to delete user comment from my web site
how to setup my Moderation tools
thnx
Hi Mahmud, great post and great work, but I’m having some problems.
After setting up all the data and setting an iframe tab and authorizing the app I stacked in an infinite redirect loop. after poking around the code I’ve found out that I’m allways get to “if (!$user) {” (fbmain.php line 44).
I stacked in an infinite redirect loop. after poking around the code I’ve found out that I’m allways get to “if (!$user) {” (fbmain.php line 44).
mahmud ahsan,
first of all, would like to thank for your wonderful site. it really help me understand a lot in terms of creating an app for us but seems like there’s a problem on a certain part which is the Like part. i did input our fanpage link but it when i checked the “Signed Request” tab in the user like this page portion, the output is “no” even though i already like our fanpage. Please do help. thanks
Great tutorial……I’ll try it
After people send invites to their friends using fb-invite code,
how to track which friends accepted invitation ?
I want to give reward points not only for sending invitation but for actual ‘result’
of ‘accepted invitations’.
Thanks much for help in advance
Great goods from you, man. I’ve take into accout your stuff prior to and you’re just extremely fantastic.
I really like what you’ve received here, really like what you’re saying and the way during which you assert it.
You make it enjoyable and you continue to take care of to keep it sensible.
I can’t wait to read much more from you. That is really a terrific website.