Facebook recently updated their PHP-SDK to version 3.0 also added new way of authentication. This is a major change. So this is the updated post of my old popular post.
In this version of my code, I avoided javascript authentication, because that is cookie based and php sdk 3.0 has some conflicts with the old system. Facebook will also update the javascript sdk soon, so later you can use the login/logout system of javascript api with php sdk. But for now you should use fully php base authentication.
In this post you’ll learn:
- How to integrate Facebook Connect in your website
- How to generate Facebook Login / Logout URL
- How to get extended permissions from users
- How to call graph api
- How to run FQL Query
- Publish Wall Post using PHP
- Publish Wall Post using Facebook Javascript API
- Invite friends using Facebook Javascript API
- No Facebook Javascript only use PHP SDK
Before proceeding:
For iFrame Base Facebook app checkout this tutorial
1. How to integrate Facebook Connect in your website
You have to create a facebook app and provide callback url. Checkout some screenshots of this article. If you unzip my downloaded code you’ll see these files (fig) where fbmain.php and index.php is coded by me. Then just copy the appid and secret key and paste them in the fbmain.php . I put all authentication and graph api code in fbmain.php and index.php is used for showing them, but remember index.php is the main file that you mention in your callback url . And this file includes fbmain.php at top.
//facebook application
$fbconfig['appid' ] = "";
$fbconfig['secret'] = "";
$fbconfig['baseurl'] = "";// "http://thinkdiff.net/demo/newfbconnect1/php/sdk3/index.php";
2. How to generate Facebook Login / Logout URL
In fbmain.php you’ll see
$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['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
and in template.php you’ll see this code. This code shows user the login and logout url.
<?php if (!$user) { ?>
You've to login using FB Login Button to see api calling result.
<a href="<?=$loginUrl?>">Facebook Login</a>
<?php } else { ?>
<a href="<?=$logoutUrl?>">Facebook Logout</a>
<?php } ?>
To learn about authentication and $user please follow this tutorial
3. How to get extended permissions from users
You’ve to provide the extended permission at the time when you generate login url. And this is ‘scope’ where you’ll provide the extended permissions as a comma separated list.
$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['baseurl']
)
);
To know more about extended permissions visit facebook official documentation
4. How to call graph api
Its very simple. You’ll see below code in fbmain.php
//get user basic description using graph api
$userInfo = $facebook->api("/$user");
//Retriving movies those are user like using graph api
try{
$movies = $facebook->api("/$user/movies");
}
catch(Exception $o){
d($o);
}
To know more about graph api visit facebook official documentation
5. How to run FQL Query
In fbmain.php you’ll see below code
try{
$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);
}
catch(Exception $o){
d($o);
}
To know more about FQL checkout facebook official documentation
6. Publish Wall Post using PHP
In fbmain.php you’ll see below code, if $_GET['publish'] is set then using php sdk and graph api the post will publish in user’s profile. You can write this code in separate php file and call via ajax to publish, in my example I use normal way to publish with no ajax. In the demo you’ll see Publish Post using PHP so click this link to publish in your wall.
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$user/feed", 'post', array(
'message' => "I love thinkdiff.net for facebook app development tutorials.
",
'link' => 'http://ithinkdiff.net',
'picture' => 'http://thinkdiff.net/ithinkdiff.png',
'name' => 'iOS Apps & Games',
'description'=> 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
d($e);
}
}
7. Publish Wall Post using Facebook Javascript API
In index.php you’ll see a javascript function
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui({ method : 'feed',
message: userPrompt,
link : hrefLink,
caption: hrefTitle,
picture: 'http://thinkdiff.net/ithinkdiff.png'
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
}
If you call this method, you’ll see a popup windows, that will prompt you to publish in your wall. In this case you don’t need any php.
8. Invite friends using Facebook Javascript API
Same as above in index.php you’ll see a javascript function. Just call this function to see a Request dialog.
function newInvite(){
var receiverUserIds = FB.ui({
method : 'apprequests',
message: 'Come on man checkout my applications. visit http://ithinkdiff.net',
},
function(receiverUserIds) {
console.log("IDS : " + receiverUserIds.request_ids);
}
);
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
9. No Facebook Javascript only use PHP SDK
If you don’t want to use any facebook javascript api, then remove all the javascript code from index.php and also remove below part
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId : '<?=$fbconfig['appid']?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
If you remove the above part facebook javascript will not work.
Hope this tutorial will help you to understand PHP SDK 3.0 and its usage properly.










i was just little confused because im new to this, but can i use this to post to users walls after they’ve joined my app? not talking about the option they get to post, i mean say a week after they’ve clicked the allowed button can i use this script to post to their wall
I need this too ! Anyone can share a way to do it ? (thanks you to mahmud ahsan for all the help you give me with thinkdiff.net, thats so great !)
i just realise its not for a website but for a facebook application (not the same aslu i think)
I have this with my old rest api :
$message = ‘my message here’;
$attachment = array( ‘name’ => ‘attachement here’, ‘href’ => ‘http://apps.facebook.com/myapp’,
$action_links = array( array(‘text’ => ‘message’, ‘href’ => ‘http://www.facebook.com/myapp’)); $attachment = json_encode($attachment); $action_links = json_encode($action_links);
$facebook->api_client->stream_publish($message, $attachment, $action_links);
but i try now SDK3…dont find how to do “auto publish stream when you accept the app
Just what I need, thanks a bunch!
When logout on the demo, it seems equal with the logout link, and refreshing the page too ¿any solution?
u can find solution for currect logout url
http://phpdog.blogspot.in/2012/03/solution-for-facebook-logouturl-not.html
find ur solution at
http://www.crashcoder.com/solution-for-facebook-logouturl-not-working/
When logout on the demo, it seems equal with the logout link, and refreshing the page too ¿any solution?
(I activated notify check now on this comment)
Probably facebook bug, because logout link is generated using PHP SDK 3.0.
hey.. The logout is having problem with me too. The logout it is creating is not logging me out of the application.
me too logout and login is never working .. any solution for this bug ?
thanks
I too am having issues with the logout? Anyone had any ideas, all we need to do is remove the cookie that’s been dropped
I also have same problem
u can find solution for currect logout url
http://phpdog.blogspot.in/2012/03/solution-for-facebook-logouturl-not.html
this logout will log the user out of facebook. but your application will not log them out. its because the data is still in the session variable .So you need to create a logout page and destroy the session using session_destroy() and then redirect the user to the main page again. and change the logoutUrl to this
$logoutUrl = $facebook->getLogoutUrl(array(
‘next’ => ‘http://yourdomain.com/logout.php’
));
Thank you for this tutorial. This code actually works and does what i want.
Keep up the good work.
how to publish using swfobject using this function?
i already try and gonna be crazy soon. hehe
any help?
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui({ method : ‘feed’,
message: userPrompt,
link : hrefLink,
caption: hrefTitle,
picture: ‘http://thinkdiff.net/ithinkdiff.png’
});
//http://developers.facebook.com/docs/reference/dialogs/feed/
yea i also ask them about them long time ago.. noboy answer this
Hi Mahmud
the php code of your old iFrame tutorial is running fine on my server but your new SDK3 code is generating a blank page without any errors. Do I need a certain PHP version on my server?
regards
Fred
Nope, my php version is 5.2. I think you’ve other problem not php base.
Facebook older PHP SDK stopped working with my Facebook Connect website.
I found this great tutorial, but the only problem is that I am getting this error:
CSRF state token does not match one provided.
because of which I cannot proceed and complete my application flow. Kindly help..
Now a days lots of applications are creating an image from images of friends and uploading them to an album.
can you post some tutorial on that ?
it’ll be really helpful !
i am aslo looking for same thing..pls notify me if u got that…..
hemanthkumar.cute456@gmail.com
How to save the data in database ? Can you gimme a hint ?
http://thinkdiff.net/facebook/users-demographic-data-from-facebook/ Get idea from here.
What would we do without you! man the definitive guide to FB app development
if i want to get user access token using ur given code, how i can get it.
print_r($_SESSION);
hope you’ll get user access token.
http://apps.facebook.com/thinkdiffdemo/
nope. it returns app request token not user access token
sorry i mean to say it returns app access token not user access token
to get access token in php sdk 3 , there is a new method getAccessToken()
$access_token = $facebook->getAccessToken();
Hello,
aboslutely great tutorial.
Everything works fine as a Facebook-external application.
Please Note: If I use the login script in a Facebook-internal (canvas page) app it will not work.
How do I detect the user in a canvas page?
check this tutorial http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development-php-sdk-3-0/
Thank you very much, an excellent start point for Facebook API beginers.
Hi I started to develop a site for a farmville group on facebook, I use php sdk 3, when we (members of the group) click the login, it logs us in but doesn’t recognize we are logged in. I had it set if($user) –showpage–else –please login– it worked fine till about 2 days ago, so what I did was show the login, and put a link to another page, told them to click the login, then the link, the other page also has if($user) –show page, but it recognizes us on 2nd page. I also added the login with faces javascript just to prove we were logged in, cause if you aren’t it wont show the faces, so now on main page, click log in, it shows javascript faces but does not show logged in… any ideas? thanks!!
hi mahmud,
i have to develop a feature on my application through which visitors could login to the site, using their facebook account, what i inititally did was to simply check the if there is a response from the FB and populated a hidden form with response.email and submitted it using javascript to a functionsay FB_login() in my users.php class
in this function i register the email as new user if email is new to user’s table and let him login if this email is present in users table.
now i found that any one could submit that hidden form with any email with action users/FB_login, from almost any html page.
what should i do, to secure my site, i am developing using cake_php.
logout not working??? any help
Wow this is sick dude, me likey thanks for sharing and not charging for all this lol
The logout problem is due to the cookie being dropped.
This code is the answer. Just insert it in your fbmain file.
if (isset($_SERVER['HTTP_COOKIE'])) { $cookies = explode(';', $_SERVER['HTTP_COOKIE']); foreach($cookies as $cookie) { $parts = explode('=', $cookie); $name = trim($parts[0]); setcookie($name, '', time()-1000); setcookie($name, '', time()-1000, '/'); } }Does this fix apply to the issue where it doesnt recognize a login?
Thanks for your information and code
This has not been a true fix for me. It creates other problems.
I think it is on the right track. Is there some way to trigger the delete cookie when the logout link is clicked?
Hi, one thing that confuses me big time, is whether or not it is possible in PHP to retrieve the posts made on my wall (in the REST API through stream.get that worked fine) using the Graph API, *without* the user needed to be logged in on Facebook (FB).
Isn’t that possible anymore, or in other words does a visitor of my website needs to be logged in to FB in order to view posts that were posted on my wall but which I retrieved from FB using PHP-SDK?
now you need an access token for your app
Hi, I followed your article and i have copied your source code to server. I havechanged the id and key values. i am able to login from facebook and it is returning to the base url. But, it is not showing the values like in your demo.. and it is not show the logout url…
The logout issues reported above are caused by the “offline_access” permission that the application asks (and recieves) from the user. Removing the offline_access permission solves the issue.
*CONFIRMED* you are correct Jeroen. The LOGOUT button works properly with the offline_access permission removed. Thank you, I have been working on this for almost 5 hours.
but should that be the case? I also removed the offiline access and it worked? That means there’s a conflict something…can’t that be rectified instead?
Does anyone know why I m getting the following error
Call to a member function api() on a non-object in {file location}
I have used the exact same code ?
Hi,
I have created an facebook app with PHP and I display a form and post data to another PHP using action attribute of form tag. But the page is not displayed. Help me. Thanks in advance.
Hi
I want to get information about the Invite button for a page. Now the FB.ui(method:’apprequests’) sends the application request. while the user click on it, it shows a page to install the same.
If I want to invite to a page of mine, hows it can be possible from iframe
Awsome help to me…
Hi,
I have problem to extract the session data.
When I run your online demo application – after I login my facebook account, I can see 4 boxex listed my facebook account info.
When I downloaded the sample code and run into my dynamic IP address website, I only have the facebook login link.
Please help.
my testing web page is @ http://69.109.165.139/facebook/test06/
I solve the problem.
I create a new app and set the site URL and Canvas URL point to my server’s testing page.
That testing page is the downloaded’s index.php
Once I login, I can see all 4 boxes on the bottom of the page with my facebook account’s info.
Got it.
Hi Richmond,
I am stuck with the same problem. I even created the new app and set the site URL to my testing page (which is index.php)
Still once I login, I get the same index.php page which asks me to login again.
URL looks something like this:
http://localhost/index.php?state=f1a2bc66485bde3dbe2842bc5…c&code=AQATXZ9iRQt…
Could you please help me here.
Thanks,
Theval
Hey Hi,
Thanks for your Tutorial. They have been so informative and helped me understand the Core functionality of Graph API.
A small Request, can you write a Tutorial on
“Authenticating user with Graph API”
I have a small problem using this. Even when a user Logs out of Facebook after logging into my application, the getUser() which i use for maintaining session still is valid and the user is still able to access my application.
How to rectify this
Dears please anyone try fb:friend-selector with this SDK please help ,
thanx aloot Mahmud , please advice about this option
fb:friend-selector is old fbml tag. Forget that.
hello,
Great tutorial!! Thanks very much for posting.
However, i am just a beginner and i encoutered a problem that spent me lot of time trying to solve it, but still can’t get it thru. I got an error msg “Warning: error_log() has been disabled for security reasons in base_facebook.php on line 987″ when i click the “facebook login” Could someone please help? Thanks very much for helping.
error_log() is a php function, its disabled in your server. So you can remove or comment the line.
hi all,
SOMEBODY HELP ME, i was searching and searching for facebook fan page publisher and no luck, now i made code to publish as fan page but i need form to be able easy to put content i want to share, i hope you understand me.
I need form to post on facebook
Hello Hadis. Did you get any help with this?
Hello mamhud.
Great work man. Just what i was looking for a while back.
But i have some trouble your code works for you, but not for me ;(
I try to get working your code. All the ID keys are mine.
But all the time i get this: “An error occurred with . Please try again later.”
As for facebook application settings: in Web Site tab i only setup Site URL and Site Domain fields like http://mysitedomain.com / mysitedomain.com
Other fields i left as is.
Please help me! Can’t solve this weird problem.
Hope to hear from you soon.
Regards,
Nick P.
Whta’s the problem do you think?
And what’s the problem if it won’t redirect me after the facebook signin process ? I am still on the same page?
It happens even with your given code….. @Mahmud help me please.
@Mahmud,
tx for the tut.
I almost got it all working except for the logout it, it doesn’t seem to do anything.
I am developing on localhost and i have the FB app setup with localhost
any info
btw how do i deauthorize??
Facebook is updating their Javascript SDK so I hope after then logout will be ok, when you’ll use both php+js sdk. Currently it might be facebook’s bug, cause we generate logout link from their php sdk.
You Are Fantastic Man
You Do Amazing Job Now Facebook is Future
Very good tutorial,
Can be used to log into facebook a button “facebook connect” fb instead of text?
Greetings.
I need a help. I downloaded your sample application and I renamed the project in “prijateli” (because my fb test application is called “prijateli”). When I click “Facebook Login” I am getting “Forbidden
You don’t have permission to access /prijateli/< on this server."
I run this project on wamp server.
And my Canvas URL is http://localhost/prijateli/
Thanks in advance.
Hey Nikolche, I have a same problem .. with login buttun .. http://localhost/test/fb2/ .. my localhost is culr.dll enabled .. then what will be the problem ? any idea?
I just uploaded it to my website, added the appid, secret and baseurl BUT I get an error:
Fatal error: Class ‘Facebook’ not found in /home/tennis/public_html/go2/fb/fbmain.php on line 24
Check If you included correctly “facebook.php”. Navigate to the correct location of your facebook.php file. Example include_once “folder1/folder2/facebook.php”;
but it is in the same folder…?
I uploaded the folder with all files just as they were and on line 18 in fbmain.php it says
include_once “facebook.php”;
as far as I know that should do it?
I find out what the problem is. You will have to enable curl extension. If you are using wamp navigate to C:\wamp\bin\php\php(Your version) AND C:\wamp\bin\apache\Apache(Your version)\bin open the php.ini files with some text editors and remove “;” in front of the extension=php_curl.dll
it look like “;extension=php_curl.dll” but it should look like “extension=php_curl.dll”. Save the files restart your server and you are ready to go
Hi, I have changed it …but it still shows the same problem
Sometimes the site loads slowly, but great material.
can u do one for new connect-js sdk?
How do I intergrate the javascript pop up login as I prefer the grace of that.
Trying to merge both you tutorials together now.
Great post! I was wondering, is there a way to force my user to enter their login credentials anytime they try to approve my app? I ask only because I want to allow users to have multiple facebook accounts hooked up to my app, but whenever I do this it just forwards them back to me because they’re already logged in with an account that has approved my app :/
iam having an auth error after i log out and view another page.
heres the scenario.
1. click logout.
2. if logout in index(home page) no error return else will return the error message
[type] => OAuthException
[message] => Error validating access token: The session is invalid because the user logged out.
3.(in index) when i click another page it returns the same error.
is there any way to prevent the message from showing or is there any way to hide the message? i think the site works well even with the error message.
btw.
i saw this message
//you should use error_log($e); instead of printing the info on browser
on fbmain.php. is this the solution?
if it is, can you please tell us how?
thank you very much.
i got it! haha. i should try it first before asking haha.
used error_log($e); instead of d($e);
thanks anyway.
Thanks
Hi, is there no other way to invite friends aside from using javascript api? i was using your previous example of XFBML/Connect and now i just noticed that $_REQUEST['ids'] are no longer functioning. I recently upgraded my PHP SDK 3.0 and my applications gone haywire.
Invite functionality is changed, using javascript new request way you have to invite.
Oh i see, so thats how it is. I am just having the problem of receiving the data requests(req thrown from my backend. is there any way to catch them from the JS?
Great work! Had such a hard time finding SDK 3 examples online!!!!
Hi, thanks for your tutorial.
My question is, How to use the page permissions to obtain the page id and the page properties ???
“Page Permissions
Permission Description
manage_pages Enables your application to retrieve access_tokens for pages the user administrates. The access tokens can be queried using the “accounts” connection in the Graph API. This permission is only compatible with the Graph API. ”
http://developers.facebook.com/docs/reference/api/page/
My idea is create an application similar to:
http://apps.facebook.com/iframe-apps/?ref=ts
http://apps.facebook.com/involver_wmzssnae/
Thanks
Hi I have a problem that I cant find answer to…
Once a user is logged into my site via Facebook, it seems that they have to reclick the ‘connect with facebook’ (don’t need to add access to the app again), if they have been inactive for a couple of hours. I’m not sure why this happens exactly, or how to prevent it?
I tried cookies… but I think I’m not doing it right.
I want that as long user connected to facebook and will visit my site the system will recognize him and he won’t have to reclick the ‘connect with facebook’ again after several hours
Hi,
Thanks a lot for your tutorial! I’m testing it on a Website, it almost work but I have some questions:
1) Logout: I had the “logout does’t work” problem, as other people do; is this definitely a FB bug? I applied the fix you mention in the comments:
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(‘;’, $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode(‘=’, $cookie);
$name = trim($parts[0]);
setcookie($name, ”, time()-1000);
setcookie($name, ”, time()-1000, ‘/’);
}
}
it works but then every time you reload the page you need to click log-in again to see the five boxes. You are just deleting the cookies right? I don’t see the point of that piece of code.
2) Could you explain this part of the code?
// 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.
So a user can be logged on facebook but with an invalid access token? When this hapen and where do you check for this?
3) What is the standard way to display facebook login – logout button instead of text links?
Thanks a lot again for all the work.
You can do it with either javascript, or you have to create an image and use the image.
thanks christopher, is there a standard picture that facebook provides for login logout?
What I did, was to use the javascript to generate the button. Then I took a screen capture and edited it in photoshop. You can even take multiple captures for different states and use your css pseudo classes to mimic the behavior of a real button.
Here may be a php solution. I have not tried it yet.
http://faceconn.com/facebook-login-button-php
Sorry another question: I noticed that in the package there is also a “page.php” file that you didn’t mention in the tutorial, could you spend some words about that? Thanks!
Great tutorial!
I’m using your ” function postToWallUsingFBApi() ” … (thanks that part was easy) to auto post to a users wall and would like to log the facebook $user id into mysql when a individual click to post to wall.
Greatly appreciated if you can assist.
Thanks
-Ryan
I have gotten your code to work on my site, but it appears to work intermittently. Sometimes I click login which promts me to enter my username and password. Afterwards, it brings me back to the login page as if I had not logged in. I click login a second time (or third) and then the page refreshes and the facebook data is displayed.
Also when I hit refresh on the page after being logged in, it takes me back to the login page.
I have the same problem. Did somebody solved it?
hey can anyone plz help me post post to a user’s wall using php sdk3 and graph. i know how to post to user’s wall but cant seem to get app to post to friend’s wall. thx. luv the website
Hi everyone! I want to ask whether the Facebook Connect login will still work even after 1st Of Oct? This is because I saw on Facebook website which says that all websites have to upgrade to OAuth2.0 as the old javascript SDK no longer be supported.
Please advise me. Thanks!
Hi, thanks for your post.
I have a problem with my app. When the user allows to give permissions, then the canvas url is loaded ouside the facebook environment, I mean it loads outside the iframe and the browser opens the canvas url alone.
Any help on this?
Thanks
Hi Mahmud ahsan,
First of all i would like to appreciate the great work done by you. Because i have been searching for the similar information on net from last 2 to 3 weeks but i didnt get right information anywhere, since i m a newbee here in this domain.
Now my question how to develop an application by which i wanna collect the public page feeds and i wanna store it into a database. I have setup “xampp” for this, i dont have any website of mine so i wanna create a web page n wanna host it by using Apache in my local system.
This may looks like a silly question for you.! but really i dont have any idea about this.. i have read about Graph API and wanna use the same here.
Please help me out..Waiting for your reply.
Thanks in advance.
Hi,
I’m using the PHP-SDK (no JS at all) but I still have some doubts about the whole process. Could you please explain better how the PHP authentication work respect to cookies?
As far as I have understood the flow is the following:
- ask FB for the user ($user = $facebook->getUser();)
- if $user is empty it means we don’t have a token, so we print out the login URL
- the login URL log the user in the system (if it’s already logged in FB) or prompts out the FB login form and then log the user into the system (if it’s not already logged in FB)…am I right?
- logging the user into the system just means setting a cookie that allows the user to navigate our site and allow us to access his FB information as requested
- from now on the two “sessions” are separated: e.g. if the user log out from the FB web site, he can still use our site as an authenticated user. Is this correct?
- logout link: it just logs-out the user from facebook, but of course not from our site since it’s all based on cookie. For that reason you proposed to delete the cookie but this prevents the system to work correctly: since it’s cookies based, if you delete the cookies every time the system ask you to click again on the login link.
Interestingly, I’ve tried to change cookie:true to cookie:false and nothing changed.
Can you please clarify those points? Saying “I have no idea” would be useful as well, we will try to find other information somewhere
It’s incredible how the facebook documentation is bad
I am using your code add appkey and secretKey
and baseurl also i put this code into localhost
url:http://localhost/sdk3_mahmud 2/index.php
I get the
An error occurred with CorkView. Please try again later.
Here CorkView is my appname
and i put code into ftp also i get same error plz help me
Never share api key, secret key with others. I removed those from your post. Check whether in your server JSON and CURL php library are installed or not. Normally without details about error its tough to guess what is happening.
I was unable to login.
I followed the steps as in website
http://www.myappdemo.com/facebook/index.php
Hi Muhmud,
Can you help me out. I am using your source cade and just inserted my app id and security and base link. Anyways when I get to th index page it always shows the login button and no boxes like your sample even though I am logged in. It seems as other people are having this same issue.
we got the code to work, but it won’t logout. even the demo doesn’t logout. fixing the logout would be a big help.
The logout was working earlier now its not working. I think this might be facebook bug. Please checkout https://github.com/facebook/php-sdk to see if anything new they suggested or follow.
Found this
“found that the following coding in the php-sdk was causing the trouble:
// prepend dot if a domain is found
if ($domain) {
$domain = ‘.’ . $domain;
}
I have commented this out and it works for me. Not sure what this code does, and why its there.”
But can’t find this line on your code.
Hi,
is there a way to skip the first step (facebook logo asking for connection) when app is not authorized
it s kinda weird , because users are thinking it s a facebook/app bug when they are already connected to facebook. dunnno what s the point with that state ..?
Hi Muhmud, thanks for sharing your knowledge.
I’ve got a problem, i followed every intruction but index.php doesn’t show any info box after i log in. Any suggestion is appreciated
you can check the problem here http://www.piazzasardegna.com/temp/asd.php
Solved, no json was not installed
Great to know that you solved it yourself.
Hi all
Awesome tutorial I’ve followed all of it, but when I use
$user = $facebook->getUser();
it returns 0, even if the user is logged in and has accepted the app request.
Any help here?
Forgive my bad english.
nevermind, it fixed itself, must be facebook problem
Any idea how it fixed itself? I have the same problem and it’s just not working. $user is 0 and I have spent all day going through code trying to see why it’s not picking up the $facebook->getUser() value…
I am logged in and I did authenticate using the Facebook Login link. A dialogue box did pop up asking for permissions so I know it’s working.
Does any of this have anything to do with the Canvas Apps now requiring SSL even if we are not actually creating a Facebook App? An earlier post suggested that they solved a problem by adding in the URL into the Canvas App configuration box. Starting on Oct 1, 2011, SSL is now required. Just wondering if this isn’t going to work without getting a certificate?? Doesn’t make sense though, as I shouldn’t have to configure the Canvas App just to get my web site to pick up information… Any ideas anyone??? I’m dying here!!!
Do you have any idea how it got fixed? I am having the same problem right now. I always get getUser() value as 0.
Also when I log in through facebook Login, I get error on that page.
Please advice.
very usefull. saved my ***, thanks!
After clicking the “Facebook logout” link, I’m successfuly logged out from FB, the fbs cookie is deleted, but my fb information is still displayed like I’m logged in because the info is stored in $_SESSION. Unless I’m getting things the wrong way, don’t you think it’d be adequate to check for the fbs cookie if it isn’t there to kill the session so the system will know the user is already logged out?
Just want to add my thanks for your great code and tutorials. I have a problem, any help would be much appreciated, Thanks.
steps to reproduce:
click login link on page, redirects to facebook login page
login at facebook page, redirects back to orginal page but doesn’t show user data – orginal page still says i have to login
click login button again, page refreshes and displays user data.
Is there a way I can get it to show the user data the first time?
Anybody else trying to solve the facebook logout problem there are some good clues here:
http://stackoverflow.com/questions/2764436/facebook-oauth-logout
How do i save the email ids generated through facebook connect on my website in a database (user login table)?
Is the a way to invite people using PHP ? It was possible in the previous versions I think. Thanks.
hello friends
anyone know how to bind facebook registration in our website.
Hy.
I use example index.php . http://dl2.zteportal.eu
Publish Post using PHP have problem.
The post only me see it as a facebook “only me” give it permissions.
Thanks for the tutorial.
Are requests (invites) only really intended for apps running inside Facebook rather than external applications that are integrated with Facebook?
I tried sending an invite to my standalone app to a friend and when he clicked accepted it went to a facebook 404 page:
(http://apps.facebook.com/APP_ID/?request_ids=REQUEST_ID&ref=notif)
How can we get this to click through to an external site?
Sir. i need to read inbox and outbox of the user can i? permission ref. is : https://developers.facebook.com/blog/post/291/ . please reply me.
khanujasunny91@gmail.com
Hai
i just try your tutorial, but why mine is blank? nothing display, even i only use this code
‘my id’,
‘secret’ => ‘my secret’,
‘cookie’ => true
));
$session = $facebook->getSession();
echo “hello”;
?>
the hello text not appear, but if i delete all except hello code it appear
can you help guide me?
this the code
<?php
require_once("facebook.php");
$config = array();
$config[‘appId’] = '275511459149629';
$config[‘secret’] = 'a92d94f1bdd6174d09a0cf24ec69d95d';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
echo 'Hello World’;
?>
please help me
How do I get the Facebook Connect/Login button to populate using the code you’ve written in this tutorial? As is, I just have a normal login button populating (which functions fine) but I’d like a Facebook Login button to render via the SDK. How do I do this using auth, is it possible?
Mahmud, Thanks for the great tutorial.
I have this sample code uploaded to my facebook app page for testing (in other words, your demo screen is shown in the canvas surrounded by the Facebook UI. The only modification I made to your code is adding Target=”_top” to prevent the Facebook login screen to be displayed inside the frame (which is ugly because the Facebook logo is now shown twice; once in the frame and the parent window). The problem happens when I hit the Facebook login link, your demo screen with boxes continues to use full window. I want this to go back inside the frame, because, after all, I meant it to be a facebook app.
You’ve to login using FB Login Button to see api calling result.
<a href="” Target=”_top”>Facebook Login
Can you tell me how I can make this happen? Thanks in advance!
Also can you tell me how to show only the “name” of the user, instead of the whole array?
I tried the following but it didn’t work. Nothing is displayed in the User information box.
In index.php,
User Information using Graph API
‘name’;
?>
This is the code I tried (excluding “//”). Didn’t work.
//
// User Information using Graph API
// ‘name’;
// ?>
//
Sorry, the HTML & PHP codes I inserted above are not shown properly. Trying again with
User Information using Graph API
?php $obj = json_decode($userinfo);
echo $obj -> ‘name’;
?
/div
Outstanding dude
In demo Facebook Logout link is now working fine, can you please correct it.
Hello All!
This is an amazing post. Thank you very much!
Now, I’ve been trying to implement this on my facebook page (business page, not user account), but it doesn’t publish on it’s wall.
Any thoughts?
Thanks in advance!
I’m trying to use some demo code (example/example.php) from the Facebook PHP SDK download on a setup with a http load balancer and 3 apache servers. The page comes up when accessed directly through the web server but does not output anything when accessed through the load balancer.
Session persistence is enabled on the load balancer. Any help or direction will be appreciated.
Is there anyway to make facebook connect work only on cookies and not on sessions..
How can I make the facebook login on a popup windows?
Can i use this with check in? or do you have a sample code w/c i can pull a check in
Hi Mahmud.
I have followed your tutorial and got everything to work. Thanks!
Do you know by any chance how to post a note to a facebook fan page that I admin?
I am using the following:
$statusUpdate = $facebook->api(‘/XXXXXXXXXX/notes’, ‘post’, array(‘message’=> ‘message’, ‘subject’ => ‘subject’));
Where XXXXXXXXXX is the page_id.
This is sort of working but it is posting the note under my personal Facebook account rather than the fan page?
I have checked the API docs and can’t seem to find a solution.
Any help would be appreciated.
Hi Ryan, I’m not sure the exact solution. Have you installed the app in your facebook fan page? If not then install and try again and get all the permissions required for notes publishing.
Hi Mahmud,
I am getting PHP Session Array in my app, but i am not getting User’s Basic Info in my app. please can u help on this issue..
Thanks,
Nazeer
I’m having the same problem that Nick had back on July 6th… What’s the answer to that problem?
I’m having the same problem that Nick had back on July 6th…
“An error occurred with appName. Please try again later.”
I downloaded your code sample, entered my appid and secret, uploaded everything to the server, logged in to facebook using my personal account and get the above error.
What’s the answer to that problem?
Answer to that problem is this: In the App editor, click on the windows check mark and put in your full domain as http://www.domain.com/ and then click save. Next put in your domain in the edit box as domain.com and you should be able to get a connection.
i have had the same problems lately, my app can no longer run
1. getUser() always return 0
or
2. “An error occurred with appName. Please try again later”
please help me
Sorry don’t read error. Is possible you need put another appName if appName is good facebook say VALID.
hello waterstorm64. I’m working with php3.0 untyl this tutorial and all go fine. What’s is the error? sorry for my english.
hi IncalB
i’m using php-sdk/facebook to create and apps and get data from facebook to my computer,
using this package downloading from: https://github.com/facebook/php-sdk
2 or 3 weeks ago, the example.php file in this package executed well,
but these days, i run it again (tried to change some app_id, secret_id in its code) and there are two errors occur:
1- $facebook->getUser() always return 0
2- “An error occurred with appName. Please try again later”
API Error Code: 100
API Error Description: Invalid parameter
Error Message: blablabla
i cant fix them
i wrote a php fangating program using php sdk, it works fine if the user is https enabled, but if the user is http enabled, it is not working, how to make fangate work even if the user is http enabled ?
Hi Mahmud!
This is a great tutorial! and this work for me, but yesterday, the button from login Facebook dosen’t work any more, I don’t know why? do you know what is hapening?
the is same for your demo:
http://thinkdiff.net/demo/newfbconnect1/php/index.php
Thanks and kind regards.
the best way to solve the logout problem is to make a logout.php file and write the following code in that
and change the logout url as
$logoutUrl = $facebook->getLogoutUrl(array(
‘next’ => ‘http://yourdomain.com/logout.php‘
));
in fbmain.php file
the best way to solve the logout problem is to make a logout.php file and write the following code in that
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(‘;’, $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode(‘=’, $cookie);
$name = trim($parts[0]);
setcookie($name, ”, time()-1000);
setcookie($name, ”, time()-1000, ‘/’);
}
}
header(‘Location: index.php’);
and change the logout url as
$logoutUrl = $facebook->getLogoutUrl(array(
‘next’ => ‘http://yourdomain.com/logout.php‘
));
in fbmain.php file
hi
can anyone here explain to me how to decode this
and pic some elements from this array
https://graph.facebook.com/me/statuses?access_token=AAACHTjIl7YsBAFwgiFtQ3KoaZCeeU7836vgBCHSZCl8W3ALvBqx29Sd37z6MSuV52IvrYmyYJUymVR9UwQw5VZA53RZCXXUbugp6Q6dh1wZDZD
is was able to store this data in a variable but how to decode this
$url =”https://graph.facebook.com/me/statuses?access_token=AAACHTjIl7YsBAFwgiFtQ3KoaZCeeU7836vgBCHSZCl8W3ALvBqx29Sd37z6MSuV52IvrYmyYJUymVR9UwQw5VZA53RZCXXUbugp6Q6dh1wZDZD”;
$post = file_get_contents($url);
i am new to Facebook api and was not able to decode the j son result
can you help me
Thanks Man.. its works perfectly
i have such code to post on my friends wall
$args = array(
‘message’ => $_SESSION['fields']['message'],
‘name’ => ‘This is my demo Facebook application!’,
‘caption’ => “Caption of the Post”,
‘link’ => $data['view_url'],
‘description’ => ‘this is a description’,
‘picture’ => $body_all["thumb"],
‘actions’ => array(array(‘name’ => ‘View’,
‘link’ => $data['view_url']))
);
$post_id = $facebook->api(“/”.$id.”/feed”, “post”, $args);
In variable $post_id i have id of my post, and then when i ask FBgraph like: https://graph.facebook.com/$post_id it`s return false… i have publish_permission, read_streem permission in my application… what i do wrong? why i couldn`t see post in info with id on Facebook graph?
Hello Mahmud,
Thanks for posting this tutorial it will be very helpful. However, I can’t seem to get the demo to work on my site.
I have uploaded all your files and only edited the appid,secret and baseurl to be http://www.mydomain/index.php
However, the link to Facebook Login on your sample page always goes to $loginUrl?> – so it isn’t resolving properly. Am I doing somethhing wrong? Do I need to download the latest PHP SDK or are your files enough?
I’d really appreciate some help – very keen to try your sample API code – Happy New Year!
Ewan Stevenson
Can you tell me how to update the caption of a photo?
I was able to upload a photo, and can set the caption at upload, but I would like to be able to change the caption later.
I’m using:
$facebook->api(‘/’.$thePhotoIdHere, ‘POST’, array(‘name’ => ‘caption updated’));
But I keep getting the error:
Fatal error: Uncaught OAuthException: (#221) Photo not visible thrown in /home/ben/public_html/gallery-admin/fb/base_facebook.php on line 1039
The scope I’m using is:
publish_stream, user_photos, offline_access, manage_pages
This is particularly frustrating because I thought I had this working last week, but now it doesn’t. Any help would be appreciated.
My app takes about 3 – 4 seconds to display anything as simple as user ID. Is it a PHP api problem?
How could I implement a javascript loading image? Thanks you.
When I logout from my app, it does not log me out of app. But only logs me out of facebook.com. I have delete cookies from my browser to fully logout of my app. I use think link to < a href="” >LOGOUT to logout.
Does any one fix the log out problem ?
There is no logout problem… its a rights/permission problem. You have offline_access and with offline_access logout will not work.
yes, I do have offline_access. so how do I fix this?
Hi! about the logout problem. I resolve the problem cleanig the cookie for mi website in the client browser.
all this tutorial is based in the server but the information is saved temporarly in the browser with the cookie. I used the logoutUrl in a link for logout user :
getLogoutUrl(array(‘next’=> logout.php));
inside my logout.php I delete cookie with a javascript something like that :
http://www.htmleando.com/pregunta/como-eliminar-una-cookie-usando-javascript
sorry for my english
I tried google to find how to remove cookie, but they are asking for the cookie name, which I dont know. can you plz upload your logout,php file. thanks in advance
Hi,
I am also having facebook logout button problem
when I click on it shows below error
An active access token must be used to query information about the current user.
. Also I did not find check box for offline access in facebook.com site in app tab ?
Is that settings are https://developers.facebook.com/apps on this page or
http://www.facebook.com/settings?tab=applications
I have activated this settings “Access my data any time”.
Thanks in advance .
Sharad.
Hi,
I have edited wp-facebook 1.6 plugin’s shortcode.php file .
I have added offline access parameter in scope variable still it does not fix logout issue.
When application is posting to a users friends wall (which this code works perfectly) the post on the wall comes from me (user logged in/admin) not from user1 to users friend. Here is the code:
require_once (‘conf.php’);
$config = array(
‘appId’ => ‘MYAPPID’,
‘secret’ => ‘SECRETID’,
);
$facebook = new Facebook($config);
$userID = ’00001′; //User 1 not me
$userFriendID =’0000002′; //Their friend
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = “https://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/$userID?access_token=”
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
$attachment = array(
‘access_token’ => $params['access_token'],
‘from’ => array(‘name’ => ‘Users name’,'id’ => $userID),
‘message’ => $Message,
‘name’ => “Greetings!”,
‘link’ => “http://www.mysite.com”,
‘description’ => “This post was made using nightly job”);
$ret_obj = $facebook->api(‘/’.$userFriendID.’/feed’, ‘POST’, $attachment);
The post should come from user1 to users friend wall. Post is coming from me because the $facebook is using the logged in credentials NOT the ‘from’ => array(‘name’ => ‘Users name’,'id’ => $userID), parameter in the $attachment that I am passing into the post. Any help/insight would really help.
Thanks!
If its using you and not the user whose supposed to be posting then you’re using the wrong authorization token. You have to use the authorization token of the person under whose account you are doing the posting for… In order for you to have a permanent token you have to have permissions for offline_access.
Thanks for the quick reply Pete.How do I get the auth token from the user?
In the code above:
$graph_url = “https://graph.facebook.com/$userID?access_token=”
. $params['access_token'];
The access token $params['access_token']; came from
$token_url = “https://graph.facebook.com/oauth/access_token?”
. “client_id=” . $app_id . “&redirect_uri=” . urlencode($my_url)
. “&client_secret=” . $app_secret . “&code=” . $code;
which is the token from my app that is authorized from the user to have offline_access.
I tried iterating through the user obj but there is no access token. So how do i get the user token? This is a nightly job the user will not be loggon on to this page.
Thanks!
When the user authorizes you, your callback url gets called, inside that callback initiate your $facebook obj then do a get access token and save that in your database.
I don’t have access to the code on this computer so I can’t give you the exact snippet but its pretty easy to find and may even have been in the authors example.
awsome man nice effort its work for my site,
best article bcaz both demo and download file working,you save my time i was finding this code from couple of days but all code was integrate with old fb sdk
Thanks for update your last article
Thanks You
You rock!
Hi bro, am getting this error
( ! ) Fatal error: Class ‘Facebook’ not found in D:\wamp\www\fb\fb_2\fbmain.php on line 24
Call Stack
# Time Memory Function Location
1 0.0018 377400 {main}( ) ..\index.php:0
2 0.0037 402944 include_once( ‘D:\wamp\www\fb\fb_2\fbmain.php’ ) ..\index.php:2
waiting for your help….
I’m having the same error after applying today’s fix.
You can wait until your teeth fall out for the author to help… I think once these projects are done he moves on and never looks back… at least that’s how it seems as he’s not posted an answer in a very, very long time.
if the class facebook is not found then you are not including the facebook libs properly. Did you download the facebook libs from github?
hi i have problem when i set all the app setting then when i m run in localhost it gives me error like this “An error occurred. Please try later”, if you have any solution then plz reply me….
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
Plz help me !!!!!!!!!!!!!!!!!!!
this my php code
$app_id,
‘secret’ => $app_secret,
‘cookie’ => true,
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$url= ‘https://www.facebook.com/dialog/oauth?client_id=’.$app_id.’&redirect_uri=http://xomcongnghe.com/APPS-FACEBOOK/tuan.php’;
$UL_goback =”http://apps.facebook.com/sharelinkhay”;
?>
api(‘/me’,'GET’);
$name = $user_profile['name'];
$username = $user_profile['username'];
}catch(FacebookApiException $e){
d($e); // d is a debug function defined at the end of this file
$user = null;
$nick_name =null;
}
}
else
{
echo “top.location.href = ‘$url’;”;
}
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api(“/$user_id/feed”, ‘post’, array(
‘message’ => “Xom cong nghe”,
‘link’ => ‘http://xomcongnghe.com/’,
‘picture’ => ‘http://xomcongnghe.com/logo.jpg’,
‘name’ => ‘It news, soft’,
‘description’=> ‘Thank you!’
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
echo “Error”;
}
header(“Location: $UL_goback “);
}
?>
and my index.php
App
body {
font-family:Verdana, Geneva, sans-serif;
}
XIN CHÀO: <img src="https://graph.facebook.com//picture“/>
Post in your wall
but i click to >Post in your wallapi(“/$user_id/feed”, ‘post’, array(
‘message’ => “Xom cong nghe”,
‘link’ => ‘http://xomcongnghe.com/’,
‘picture’ => ‘http://xomcongnghe.com/logo.jpg’,
‘name’ => ‘It news, soft’,
‘description’=> ‘Thank you!’
)
);
not working
step to:
catch (FacebookApiException $e) {
echo “Error”;
}
plz
I am working with a app which uses the offline access to post as the user using the accesstoken in to facebook wall ,but now the facebook is depreciated the offline access ,so that i cant get the offline access to do so ;the facebook document is unclear and i hav trird the document codes,but no hopes. so is their any one to help me to extend the offline access expire period of both new user and already using one.
facebook publish is not working ?????
Fatal error: Uncaught CurlException: 1: Protocol https not supported or disabled in libcurl thrown in /home2/XXXXX/src/base_facebook.php on line 886
All the sudden I am getting this error. my host do have cURL enabled. I am using updated php sdk.
anyone solve this issue
It is also much shorter and easy to use the latest version of PHPforFB framework (http://www.phpforfb.com/en/).
Description taken from homepage:
“PHPforFB is a PHP framework that helps to simplify the development and operation of Facebook applications (and page extensions). By the help of this framework, you can write and publish Facebook applications quickly and efficiently, while only basic PHP and web knowledge is required. The benefit of PHPforFB framework is that you have only marginally to deal with Facebook® server communication and its respective interfaces. Instead, you can concentrate on the development and functionality of your application. The PHPforFB framework provides the Facebook® functionality and access to its interfaces, which are indispensable for an Facebook® application.”
Hello, could you tell what settings you need to put in an application, so you can send messages to the wall of the user if he logged on my website. Please petition for my clumsy English. If you have no trouble could you send instructions on a-l-b-e-r-t-i-n-o@ya.ru
Hi, my question is about in point 6:
your code is =
if (isset($_GET['publish'])){
”,
try {
$publishStream = $facebook->api(“/$user/feed”, ‘post’, array(
‘message’ => “I love thinkdiff.net for facebook app development tutorials.
‘link’ => ‘http://ithinkdiff.net’,
‘picture’ => ‘http://thinkdiff.net/ithinkdiff.png’,
‘name’ => ‘iOS Apps & Games’,
‘description’=> ‘Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!’
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
d($e);
}
I would like know how to automatic publish in wall.
without pressing any buttons or links
thanks you
’3******************5′,
‘secret’ => ‘be*********************e2′,
‘fileUpload’ => true,
));
// Get User ID
$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.
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;
}
}
$params = array(
‘scope’ => ‘email,user_hometown,user_birthday,user_interests,user_likes,user_location’,
);
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($params);
$uploadSupported = $facebook->useFileUploadSupport();
$facebook->setFileUploadSupport(true);
$img = ‘example.jpg’;
$photo = $facebook->api(`/me/photos`, `POST`,array(`source` => `@` . $img,`message` => `Photo uploaded via the PHP SDK`));
}
?>
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.
how to login to facebook from back end with php
Hello,
I am wondering if you would create a script for me that will allow users of my service to be able to post (scheduled status updates) or messages to their fans on a fan page.
They would log onto my service where I would store their FB username and password. I would then have a cron script that would identify when the post/status update should be made. The script would run, log the user into FB and change status or post to wall.
I’m willing to pay for this script to login and post the mysql value into FB.
Thanks!
<?php
$app_id = "dsfsdfdsfdsfsdfsdf";
$app_secret = "sdfsdfsdfsdfsdfdsfsd";
$my_url = "http://example.com/test/";
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);
echo “”;
print_r($response);
$params = null;
parse_str($response, $params);
/*echo “”;
print_r($params);*/
$graph_url = “https://graph.facebook.com/me?access_token=”
. $params['access_token'];
echo “” . $graph_url . “”;
$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.”);
}
?>
I got an error: {“error”:{“message”:”Error validating verification code.”,”type”:”OAuthException”,”code”:100}} Please respond
This place:
http://rwsdev.net/2012/01/facebook-app-and-user-management-class-fbappclass-for-facebook-php-sdk-3-1-1/
is using at least some of the same code appearing here, but you are both claiming copyright of the code. Who’s code is it, I wonder?
hello, anyone know why the index.php is blank? If I change the redirection to fbmain.php appear login links, but of course, does not work. So I think the problem may be in the file fbmain.php.
I am having the same problem as some of you mentioned before.
I always get getUser() value as 0.
Also when I log in through facebook Login, I get error on that page.
Please advice as I am stuck at this point.
Error on Login page is solved. But I still get user value as 0 and hence nothing is displayed on the page.
Hi, I solved the problem by updating the php version on my server. Thanks.
Hey thanks… i am working on ubuntu and I updated the php version. I feel the problem is with the redirection after login. Do we really need to make a virtual host?
Right now my site url looks like: http://localhost:80/index.php
Hello, can someone help me.
I am using localhost to test my project.
I am getting this error :
Access forbidden!
You don’t have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
localhost
3/22/2012 2:28:44 PM
Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
Thanks for help.
i believe its due to the fact that they depricated the offline access tokens.
Hi i was wondering, is the ‘redirect_uri’ have to include the index.php extention in the URL if the domain is attempting to pull index.html before index.php therefore i cant just go to mydomain.com i have to go to mydomain.com/index.php
any help is much appreciated… the reason i am asking is because no matter which ways i try to attempt to use Facebooks Authentication login methods weather it be using only JavaScript or PHP either way when i click the login button its giving me a “An error occurred. Please try again later.” when im redirected to facebooks page, and it doesnt open it up in a pop up it loads a new page (same tab)
u can find solution for currect logout url solution
http://phpdog.blogspot.in/2012/03/solution-for-facebook-logouturl-not.html
i was able to use $facebook->destroySession to end the log out session. I am however one other issue now, if i login, im redirected to to my next page which is great. Im authenticated, permissions are given, but however, if i were to press back, or say open up another tab and go to my main page where i were to login… im not logged in and im forced to re log in.
also is it wiser to stick with session only? Or can i use session and cookies, because if i can use cookies that makes my life so much easier right now lol. I was told they might depricate cookies? or maybe im being misled?
How To Post A Message On The User Wall Using Facebook Graph API
Hi All!
I was going through this tutorial (http://www.masteringapi.com/tutorials/how-to-post-a-message-on-the-user-wall-using-facebook-graph-api/33/) and was trying to figure out how do I post a message on my friend’s wall using the FB Graph API.
I was able to post messages for friends who have authorized my App (clicked on teh ALLOW button of my app) but I am not able to post on my friend’s wall who have NOT allowed my app.
So my questions are:
1) Is it possible to post a message on a friend’s wall who have not authorized my app?
2) If yes, how do I do this?
3) If no, then is there any alternate way? Actually I am trying to implement a feature in my application that will allow the users to invite their friends.
Please suggest
How To Post A Message On The User Wall Using Facebook Graph API
Hi
I was going through this tutorial (http://www.masteringapi.com/tutorials/how-to-post-a-message-on-the-user-wall-using-facebook-graph-api/33/) and was trying to figure out how do I post a message on my friend’s wall using the FB Graph API.
I was able to post messages for friends who have authorized my App (clicked on teh ALLOW button of my app) but I am not able to post on my friend’s wall who have NOT allowed my app.
So my questions are:
1) Is it possible to post a message on a friend’s wall who have not authorized my app?
2) If yes, how do I do this?
3) If no, then is there any alternate way? Actually I am trying to implement a feature in my application that will allow the users to invite their friends.
Please suggest
find solution to logout url not working
http://www.crashcoder.com/solution-for-facebook-logouturl-not-working/
The sdk Logout method works just fine and the code posted in the page you linked is totally crap, altought I’ve seen it posted already here.
I don’t know where you found it, but the $facebook object construct part is missing, also the $facebook variable is undefined in the get_logout_url() function scope, and the rest looks like some bad copy/pasta of other codes in an artistic cubist fancy manner.
Invalid or no certificate authority found, using bundled information……is never ending error i don’t know why…..im trying to have Facebook connect and users data stored in my database and i thought this tutorial is great for me but here m not able to move forward….waiting for ur reply thank
Muy buen ejemplo acaro muchas de mis dudas, esta genial y con muchos tipos de interacción hacia facebook, saludos
hi,
i’m italian so excuse me for my english
can you please write how can i see the list of all friends that has an user that login with facebook from my website?
Thanks
hi,
i’m italian so excuse me for my english
can you please write how can i see the list of all friends that has an user that login with facebook from my website?
Thanks you very much
Thanks for posting this tutorial it will be very helpful!
Hi,
I followed your article and i have copied your source code to server. but the result is diferent with your demo link.
In demo link can graph email user
[gender] => male
[email] => zongvoc_05@yahoo.com
[timezone] => 7
, but on my server can’t retrieve email on array.
[gender] => male
[timezone] => 7
where is the mail key?
Any ans will be helpfull for me…
Solved :p
Good to know
All your excellent manual I added to my CodeIgniter session but one thing happens if you want to leave you to login http://www.ibsegundamano.es/facebook_test/ pruebenden logs on logs on ok but when I reloaded the index, and continues to login to finally re-enter login will give you logearon ok. Why is this? my twitter is @ incaib thanks for your valuable tutorial. Greetings from # Mallorca.
Why i get this message?
FacebookApiException Object
(
[result:protected] => Array
(
[error_code] => 1
[error] => Array
(
[message] => Protocol https not supported or disabled in libcurl
[type] => CurlException
)
)
[message:protected] => Protocol https not supported or disabled in libcurl
[string:Exception:private] =>
=> 1
[file:protected] => /home/fandesig/public_html/fb/base_facebook.php
[line:protected] => 814
[trace:Exception:private] => Array
Yeah, i get the same too..
FacebookApiException Object
(
[result:protected] => Array
(
[error] => Array
(
[message] => An active access token must be used to query information about the current user.
[type] => OAuthException
=> 2500
)
)
I think this is temporary problem, not sure. Because just now I’ve checked and found everything is ok.
i think cause of this problem, there seems to be in session duplicate..
I try again but same error, is the problem with server setting in CPANEL?
Thank you for tutorial. I have integrated facebook login to my site and seems to be working fine except few minor glitches.
Lets assume If I am login with facebook on my site. I open a facbook page in a new tab and logout from there. Now when I click any link on my site an error is generated.
“CSRF state token does not match one provided.”
This happens only for the first link clicked after logout.
I am not using any database or session to save any data.
Will you guide me how to solve the error?
Hi, thank you for this! it’s big help
Hi boss,
I am developing facebook app ..
m using sendRequestViaFriendSelector() function in javascript to send a app requests to friends ….
My query is
—————————————————————————————–
But i want to restrict user to send the request to friend multitple times.
Means he cannot able send him app request again
and users who are already using this app
—————————————————————————————-
please help as soon as possible in this regards
Hi boss,
I am developing facebook app ..
m using sendRequestViaFriendSelector() function in javascript to send a app requests to friends ….
My query is
—————————————————————————————–
But i want to restrict user to send the request to friend multitple times. |
Means he cannot able send him app request again |
and users who are already using this app |
—————————————————————————————-
please help as soon as possible in this regards
Hello, I have problem and can’t solve it all day :/ I using your code, everything works great.
After log in facebook back to the page. $user=true then I refresh the page or go to href=$LoginUrl; once again. Why it didn’t work in first page load? Maybe facebook slippage to set the user as connected ? Would anyone have any ideas how to solve this problem.
How to do this facebook login in a pop up window?
mahmud, thanks alot!!!!!!!
i was googling more then a week trying to get ‘live examples’ that really works, and luckly i found your post!!! thank you !!!!
Is it possible with this script to update a business page. Business pages appear not to have access to API key or secret.
I’m trying to access insight data from a fan page that I’m an admin for. I’m having trouble retrieving data such as ‘page_fans_gender_age’ . From what I found there’s 2 OAuth codes(one for your page and one for fan pages) I have both and have the app access token as well.
Sorry to bug you on an old post of yours but some guidance would be much appreciated.
Ok so I figured it out. I needed to connect my app to your fan page. Basically I went into the Edit App option and added the url under the ‘Page Tab’. From there I I added this script which would allow you to click ‘Add to Page’ and choose which page you want to connect with. From there calling Graph Insights was straight forward.
I forgot where I got the script so I’m sorry if I didn’t reference you if it’s yours.
I apologize Mahmud if I’m not suppose to post this but It helped me out and hopefully it will help someone else.
Add to Page
FB.init({appId: “461347150572949″, status: true, cookie: true});
function addToPage() {
// calling the API …
var obj = {
method: ‘pagetab’,
redirect_uri: ‘http://neckbeardgames.com/index.php’,
};
FB.ui(obj);
}
hi i am totally new developer can you lead me the right way how i can develop fb api
i think i can use it for my site nice post !!
Hello
I used your examples, index.php and fbmain.php in windows enviroment. When I move to linux, it stop to work. we I try the link “facebook login” I receive a message object not found and the address that the page try to go is: http://localhost/
Any ideia?
Thanks
Paulo
http://localhost/
localhost with the loginUrl tag
what can i do with this exception :S:(:(
(#368) The action attempted has been deemed abusive or is otherwise disallowed
hey guys check this out
http://learnwebscripts.com/how-to-login-into-facebook-account-using-php
its very easy to integrate
hye..1st of all..thank you for this great tutorial..it helped me a lot..i just need a lil bit help..
i got 3 php included in the index.php, which is top.php, content.php and footer.php
i have included fbmain.php in the top.php .. the login link is at top.php ..
logged in with facebook just fine..
but the problem is, i can’t echo $user in the content.php .. even tho the page is included.. i checked the included file with php’s get_included_files() function .. and facebook.php, fbmain.php dan basebook.php is already included..
so if it is included, i should be able to echo $user from content.php or footer.php right?
i appreciate all the help i can get..thank you!
THANK YOU SIR!!
you saved 3 hours of my wasted time with your great example.
i love you.
Thanks for your information and code its very helpfull
Mahmud,
Thank you very much for this tutorial. It’s very informative and much better than facebook’s own documentation.
Question: Is it possible to get a feed of your own facebook page/account using the SDK without having to use the login button? I have a general facebook page that I would like to show a feed of my status.
I was able to do it with this code, but I cannot have the user log in since I just want to show my own feed.
Thank you again!
having issues with this:
heres my fbmain.php http://pastebin.com/mxEgg5nz, yes i have changed me key from this one:
i did have it logging in, but then was receiving an OAuth error.
mahmud ahsan how can i print my credential which get from facebook after login through my app on facebook
how to print my emial address, date of birth and token and other necessary information
api(‘/me’);
$fbuser['first_name'];
$fbuser['middle_name'];
$fbuser['last_name'];
$fbuser['gender'];
$fbuser['birthday'];
$fbuser['email'];
echo ” “. $fbuser['first_name'] .”";
?>
thanks jeff but i don’t know in which file i have to place these lines
You are a great !
Thank you very much
just i have 1 problem and i try to find solution for it :
If the visitor is trying to login but he is not register to my APP
facebook will redirect him to example.php page without asking him to accept my App and register
in other words i only need to let my current user to path from the Fblogin url and if he
not a user then i will redirect him to other page without asking hem to register for my App
Could anyone help me please ?
Thanks
Amazing! Its actually remarkable article, I have got much clear idea on the topic of from this piece of writing.
Hello, I’m trying to get all my albums with your script .. it works and then after some seconds, my page goes blank. How can I achieve that.
My code in fbmain.php
$albums = $facebook->api(‘/me/albums’);
foreach($albums['data'] as $album) {
echo ‘‘.$album['name'].’‘.” ;
}
I am trying login by Facebook at local host. All step works but i don’t get logged user data. Every time $user variable returns 0. How can i solved that.
My fbmain details:
$fbconfig['baseurl'] = “http://localhost/FacebookMaster/index.php”
and at Facebook —
Website with Facebook Log in —
Site URL: http://localhost/FacebookMaster/
Please help me.
Awaiting quick response.
Excellent piece of code and it did what it said it should do. Yes there were a few issues, so reading through the post I eventually managed to solve them.
Thanks again
John
thanx to provide this information
Thank you so much for this very helpful article!
It did the trick in helping me setup and understand the new facebook login process through php sdk!! Win!
This design is spectacular! You most certainly know how to keep a reader
entertained. Between your wit and your videos, I was almost moved to start my own blog
(well, almost…HaHa!) Great job. I really enjoyed what
you had to say, and more than that, how you presented it.
Too cool!
Gracias por el tutorial, esta genial, he probado con el API javascript y no funcionaba del todo bien pero con este codigo soy mas libre de manipular la info a mi gusto.
Saludos
thanks for the nice tutorial, much easier than starting all together.
I have been looking for the easiest way i can implement this and i finally found it. thanks for that.
i watched your demo after that i have download your source code after that i have create my new app in facebook i have capture App ID and Secret key and given permission which is given in login url scope after that i have run code their is error is comming when click on facebook login link error display in browser http://localhost/fbk/%3C?=$loginUrl?%3E
Forbidden
You don’t have permission to access /fbk/< on this server. so i requested to you please help what is the prob what should i do ? ASAP reply me! thanks in advanced
Since shampooing and regular conditioning is important for cleansing the dirt and
oily accumulations, rinsing your hair with the Macadamia Natural Oil Rejuvenating Shampoo on a regular basis can
act wonder on your hair by converting any type of lifeless
and frizzy hair into smooth, silky and shiny that is free of damage.
For liquid filled transformers the approach is similar.
Exposure to the sun’s ultra-violet rays can trigger the release of free radicals that hastens aging and appearance of wrinkles.
Thank you very much. I have tried several codes, but yours is the only one who worked.
Thank you, this is what I looking for. But, it’s updated 2 years ago. Any changes? Thanks.
is it possible to make auth popups in single pop up. I am using publish_actions,publish_stream in scope but its coming in second pop up only.(publish_actions,publish_stream)
These oils are extracted by steam distillation or expression from
the roots, stems, leaves, petals, fruits or nuts of the plant.
When I say youthful, I am not implying that a 50 year old woman becomes obsessed with looking thirty.
Unfortunately many facial creams on the market, even the expensive, ones contain mineral oils.