Facebook has announced and released a new PHP SDK to use on the platform, making significant changes to the way developers can access the API and the new Graph API 2.0. The new PHP SDK splits the functions into multiple classes, so you only need to include the classes you need.
Basic Example
In essence, making API calls and getting data has changed significantly. Just look at the sample code below which asks the user to login and prints their profile data:
You now need to include each individual class you require (require_once
), set the namespace alias (use
) and then calling the functions you need to achieve login and retrieval of API response.
Chaining
The good thing is that the code can be reduced from the example above using chaining. From the example above, you can turn lines 92-95 into just one (large) line. Take this example:
The new SDK will definitely take a while to get used to. In fact, the new documentation already has a few errors in it that makes it difficult to even get started…
Additional Permissions / Scope
If your application needs additional permissions from the user, you can pass these in as an array to the $helper->getLoginUrl()
function. The first parameter takes an array of permissions like the example below:
Note: The Facebook PHP SDK 4.0.0 contains more classes than used in the example above, but I’ve included the minimum number needed to achieve login and retrieval of profile information.
Logout Page
For those asking about how to log a user out from your application, you must clear the session or delete any cookies you set. In my example, the following is required on the logout.php
page to clear the user’s session.
Update #1
8th May 2014: The original code in this post has been updated to include session management. The new code now remembers any saved access_tokens, validates the token and makes an API call without asking the user to login again. The code works for the changes included in Facebook PHP SDK v4.0.1 and v4.0.2. The new code also includes an extra line to generate the logout link for the user.
You can see the changes to the code here.
Update #2
21st May 2014: Facebook has yet again updated the Facebook PHP SDK, this time to version v4.0.5. The new changes are significant, adding a number of new files that are required for the Facebook SDK to work. I’ve updated my sample code yet again to account for these changes.
You can see the changes to the code here.
27th May 2014: Newly released version v4.0.6 continues to work with the above sample code.
Update #3
10th June 2014: Facebook has updated the PHP SDK to version v4.0.8. The new changes mode some of the classes into a sub-folder, breaking existing code. The below snipped shows how the class includes and use
statements needs to be changes:
11th June 2014: New tutorial on how to create Facebook Tab Apps has been added. Required Facebook PHP SDK 4.0.7 or later.
Update #4
27th June 2014: I’ve made a change to the initial code to deal with session errors. Essentially, I’ve changed the first <code>IF…ELSE</code> statement into two separate <code>IF</code> statements to deal with session errors, like expired sessions. You can see the changes separately here.
Facebook has also made further changes to the SDK but failed to tag the new version as v4.0.9. Therefore my modifications in Update 3 has been updated to include the further file changes in the same version (v4.0.8). You can see the modifications separately here.
Update #5
27th October 2014: Added logout.php
code due to multiple requests.
I don’t understand the login url bit. What are we supposed to use here?
$helper = new FacebookRedirectLoginHelper( ‘http://localhost/php-sdk-4.0/’ );
What would I use as my url? Anything? In the previous API, you would put the scope of permissions, etc… and that would generate the login url. Is there a new call similar to getLoginUrl() from the previous API?
Your redirect_url would be where you want your users to end up after they’ve logged in. My example is using a local URL, but this can be changed to any page within your application.
You can add extra permissions to the login by doing:
$helper->getLoginUrl( array( 'email' ) )
I’ve updated the article to include some sample code for this.
Awesome, this helps a lot.
Also, I was initially having an issue with the $session variable. My problem, is that my app was having to hit the redirect for ‘every’ call. In other words, it would always show the ‘Login’ link from your example. I posted on SO, and the recommendation was to save $session in a PHP session ($_SESSION[‘fb_session’] = $session), and use that for subsequent requests. However, we know that the access token / session expires… correct? So, now my problem is that I have an old FB session stored… what is the best way to check if I need to request a new session?
You can validate the session by first passing the saved access token into the FacebookSession class, e.g.:
Then, you can use the
$session->validate();
function to check if the session is valid, e.g.:If the session is invalid, I set the
$session
to null so the rest of the code can continue to execute and ask the user to login again.Can’t figure out how to include the files. The latest update comes with such poorly written documentation!
Have you tried using the example above? We use require_once to include the required files for the example. You can include the other files in this way.
I’m using the require_once in my code, but when I try to use the “use” statement, my code editor sees it as an error and the page goes blank when I execute it. I’ve even tried moving the Facebook SDK to be in the same directory as the file that’s being executed and it won’t work. I’m trying to build this into a WordPress site so I hope that doesn’t have anything to do with it.
What version of PHP are you using? To use the new SDK, PHP v5.4 or higher is recommended. Please check you have a compatible version.
its do not work, i copy and paste this code in application index.php but when i open my application url it say nothing
What errors are you seeing? Did you copy the src of the Facebook SDK to the “Facebook” folder?
i copy and paste this code in index.php, of course i edit application ID & key but when i upload it on my host and run in browser say nothing. facebook php sdk file is in Facebook folder
I have the same issue. Nothing is shown. Facebook SDK set on my web site. App created and api keys set in the index.php. It is like echo is not showing anything ….
Do not understand.
Best Regards.
This suggests that the page is encountering some sort of error and you may have error reporting disabled. Please add the following two lines to the top of your code and see what errors you get:
I have this error reporting set and am getting the same thing. A completely blank page. If I remove the “use” statements, I get an error stating it can’t find the FacebookSession class. This new SDK is really infuriating.
Try deleting any cookies on your page to see if the session is causing a problem. Also, read my other reply and make sure you are using PHP 5.4 or higher.
Niraj Shah,
Thank you so much for this. It helped alot. I have a question and maybe you can guide me on to right path. I was reading facebook guidelines and they as that users must give permission to allow your app to use their content and if denied to request once more. How would you request permissions and gather the returned fields? This is my current dilemma.
The above code will return all the profile information for the user if they’ve given you permission. If they deny the initial request, you should ask them again by either reloading the page or triggering another login call. If they reject it twice, you should not ask them again.
I get — Parse error: syntax error, unexpected ‘use’ (T_USE)
The use keyword is available in PHP 5.3.0+. Make sure you are using a compatible PHP version.
Also, use must be used outside of a function or class. Make sure it is used in the correct place.
Hi!! Can you write a full code to get user email
Edit: OH! sorry I had not read all the code.
Cool demonstration to get for permissions, I was having trouble to get this work. Unfortunatelly because I’ve already approved the app with basic permissions and I’m logged in, now when I ask for extra permissions, nothing happens, popup to update permissions is not triggered. I was wondering how you will logout with the new API?
To log a user out, you can make a similar call to the
FacebookRedirectLoginHelper
class:You need to pass in the
$session
parameter (created on login or from cookie) and a URL to redirect the user to after logout.I’ve updated my code to include this.
Thank you for the tutorial. I was able to implement it and it works great.
I have a question.
How do you get the $_SESSION[‘fb_token’] ?
Am I supposed to do this ?
$_SESSION['fb_token'] = $session;
I tried using you code in comment #228 to validate a session, but its not working. I’m confused on how to store the facebook token in a php session variable.
I’ve updated the original code to include session management. It shows you how you can load an existing session or create a new one.
Wow, Facebook is a multimillion dollar company and they couldn’t provide complete working examples for PHP like you did. Thank you for helping us understand their api better.
can you use v4 to pull out events by event id? The documentation is shocking.
Yes you can. As long as the event is public or you have permission to view the event, you can do something like:
Hi Niraj,
I was running your example locally, and it worked, thanks! I have though PHP 5.5 locally, and it is 53 on our live server. And it doesn’t work with 5.3 it seems.
Is there any changes I can do in the Facebook code to have it to run on 5.3 also? What does version 4.0 use in PHP 5.4 that 5.3 didnt have?
Although the Facebook documentation doesn’t mention it, the new SDK requires PHP 5.4+. But I haven’t come across what functions it uses from that version of PHP that cannot be found in earlier versions.
The only requirement I see for the need for PHP 5.4 is the following syntax:
(new FacebookRequest( $session, 'GET', '/me' ))->execute():
Its used within the Facebook classes, and could be the reason why it doesn’t work with PHP 5.3.
Thanks, u seems to know really much about this API? Let me know if u do consultings. We could need help on small issues. We get stuck a lot in facebook api, and the documentation is almost better not to read, since its wrong mostly 🙂
Yes, I offer consulting services. Please email me the details and I’ll see how I can help.
i tested your code but i have the same problem as my code. when user login nothing happens and just the url changes . is it out going connection problem?
Add
print_r( $ex )
to Line 56 and see what error you get from Facebook. It might give you a clue as to what is going wrong with your code. Also, make sure you’re using PHP 5.4+ as that is required for the SDK to work.i got this error “Fatal Error: type: OAuthException, code: 5, message: (#5) Unauthorized source IP address ” and ive add the ip to white list and this error disappeared but now no error coming and same problem nothing happen
Try removing all the IPs from your whitelist and see if it helps. The whitelist is only used if you’ve entered at least one IP, otherwise the platform ignores the list and allows all access. Once you get it working, make sure you are using your server IP address instead of your local IP address.
Hi Niraj.Thanks for this nice work. i am getting an empty error when i want to get friends lists. Instead of
$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );
i am using
$request = new FacebookRequest( $session, ‘GET’, ‘/me/friends’ );
The friend list isn’t available as default anymore with the new Graph API 2.0 and PHP SDK. You now need to ask for the
user_friends
permissions when logging the user in.Furthermore, the Graph API will now only return mutual friends who use the application. You can no longer retrieve the entire friends list for a user, which means you cannot determine the number of friends a user has or see who they are.
You can test this by asking a friend to login to your application, and then retrieve your friends list. You will find that only your friend will appear on your friend list, all other friends who don’t use your app will remain hidden.
Is there a newer working list of which permissions to use for different requests when using the 4.0.x api?
The permission documentation has been updated to include the new permissions and the review process when using extended permissions. But as ever, its confusing and requires jumping around the very long page.
Hello,
Hi to log-in user to app on canvas page? Because there’s no getLoginUrl in FacebookCanvasLoginHelper.
Hello, thanks for the example. It works great. I just have one problem. I used your example but when I try to perform an api call I gent this error “Fatal error: Call to a member function api() on a non-object”.
I was testing the example facebook provided:
$response = $facebook->api(
“/v1.0/me”
);
Not really sure what I am doing wrong.
Thanks.
You are mixing PHP SDK 3.x code with PHP SDK 4.0.x code. Use the full code provided – I’ve given an example of how to get the profile data using the new methods.
Hi Niraj, your example code, thank you very much for doing this job… but I have a question for you… in this piece of code:
$helper = new FacebookRedirectLoginHelper( ‘url’ );
I put a link to a page of my web but I have seen in your example code it have a few echo’s but I dont know why, I can’t see them in the page I have put… can you explain me how to put the information obtained of the user (me) profile on that web?
It works fine on Firefox, but doesn’t work in Chrome nor in Safari (Mac OS). Any ideas ?
Well points to you Sir. Not only did you solve my confusion about this new facebook api, your code example actually worked on the first try. That is just so rare.
Hi is very interesting!
How I can upload a photo to a page’s album? Uploading via form.
I’ve setup my application to use publish_action but I obtain a permission error with the example code on facebook developer page.
Thanks
Hmmm, is birthday not part of the core any more?? Says it is here. https://developers.facebook.com/docs/graph-api/reference/v2.0/user
Birthday is a core part of the API, which means it will be versioned correctly if things change. It does not mean you can access it as part of the “public_profile”. You need to ask for the “user_birthday” permission to access this field.
Thanks. The original facebook for php tutorial is poorly documented. Your tutorial saved me a lot of time.
I’m new in Facebook APIs, and i just don’t understand WHY is there nobody who has created a simple and detailed documentation for this. The Facebook docs suck for PHP SDK 4, and there is no damn tutorial for a basic setup.
This is the reason why I wrote up this tutorial. Does it not meet your needs?
I’m sure your tutorial is an easy one Niraj, but since i am a very new developer, i am just not getting it. Can i please ask you some basic questions?
The SDK 4 file, when extracted from the zip, gives two folders, one is ‘Facebook’, and another i think is ‘test’. Now what do i do? Do i use ‘Facebook’ folder as the root and make a new file called index.php and paste your above mentioned code?
I know this might be annoying for an experienced guy like yourself, but i’d appreciate of you could help! Cheers!
You should have two folders from the zip: src and test. You can create a index.php file anywhere you want, as long as you including the files using the correct path. I recommend copying the Facebook folder from within src and create an index.php file outside of it.
This tutorial assumes the all the files you need are in the Facebook folder, with index.php outside of it.
Thank you for your reply, Niraj.
So i have been on this issue since 2 days non stop, and i now can use the SDK 3 (which does not have any documentation now *yay*). But when i try to use SDK 4, i just get a blank screen! I have done everything as specified, and i am using Heroku as a host whose PHP version is 5.5..help!!
( P. S – and yes, i am using the correct AppId, correct secret, and putting the correct values as domain and URL)!
Try adding the following lines to the top of your code, incase errors have been disabled / hidden:
You may be able to get a better idea of any errors that were previously hidden. Also, in the
catch
statements in my code, addprint_r( $ex )
to see any exception errors too. The Facebook PHP SDK 4.0 was also recently updated to v4.0.5, which includes code and file changes. My code has been updated to reflect those changes, so see if the new version works for you.OK, well i am now using SDK 3, as it works for me. Could you tell me how i can use the “user_friends” permission? The syntax with the API please? Facebook docs show
$ret = $facebook->api($path, $method, $params);
and i believe it has to be somewhere in the $method parameter. I’d like to access the events that all my friends are going to. Can you help me on this?
Many thanks!
If you are using the Facebook PHP SDK 3.0, you must use the scope when logging the user in, not when making an API call. You can do this as follows:
This will show the user the login url with the correct scope added. Please edit the scope as necessary, separating each permission with a comma.
Wow, added to ‘scope’ to my login and.. now the app pop-up displays that the app will access the friends list and email.
But i still cannot print the friends who are using this app. All i want to do is extract the list of people, and the events they are going to, who are using this app. Could you help me with this too, master 😛
Here is my code ->
I don’t see you requesting friend information in your code. It’s the reason why your code isn’t working.
I see. Could you please tell me how can i request the friend’s information? I just need to retrieve the list of the events they are going to!
I know i am asking too much, but i’d appreciate if you can help me! Many thanks!
I’m not going to write custom code for you, not unless you want to pay for consultancy 🙂
haha, okay Niraj. I appreciate your help till here.
Cheers!
Hi, great article!
Question though, I used my root domain name for the redirect..am i supposed to get something else printed out to the screen besides ‘Login’ once ive logged in through facebook?
When i login and it redirects back to the index.php page it just has the login text link with a larger url in the browser. Sorry Im really new with this fb sdk stuff.
Do you have an example of the logout page needed?
I want to check and see if a user likes a certain fan page id and then echo out html code based on whether or not they like the fanpage.
Thanks
Yes, the contents of the page should change to show you the user’s profile information. If the login link is still visible, something has gone wrong and the user isn’t actually logged in.
The logout page can be quite simple, I created mine like so:
Hello Niraj,
Do you know how long the old version of the SDK will be available? I see that it depends on Graph API 1.0, and the documentation says that new apps need to use 2.0, but I just tested it and the old one works on a new app.
I am definitely switching to the new SDK for new apps in the future, I just want to know how much time I have. So will it be available while Graph API 1.0 is available, or is the current availability just a grace period?
Facebook has said that the v1.0 version of the API will be supported until 30th April 2015 – exactly one year after the release of v2.0. From then on, all apps will need to use the v2.0 API instead. For now, making a call to the API without specifying a version will use the v1.0 API until it’s completely depreciated in April 2015. You must manually specify that you want to use v2.0 of the API for the time being.
Hello, and thank you for this tutorial.
Everything works very well intended but I still have a problem.
When I allow the application, I am redirected to my web page but it was empty.
A blank page without any explanation, can you help me?
error ==> Fatal error: Class ‘Facebook\FacebookCurlHttpClient’ not found in /Applications/MAMP/htdocs/DeKnyfGregory/Facebook/FacebookRequest.php on line 154
It looks like Facebook have updated the SDK yet again, adding more files to the ZIP. I’ve updated my sample code to include the changes in v4.0.5. Please use the new code and your application should work.
I’m still using 4.0.4, will switch to 4.0.5 later this week. Will they turn off previous versions of the 4.0.x api soon or are they safe to continue using into the future?
You can continue to use older versions of the API, but it’s probably safer to use the newer versions as it’s likely to include bug fixes and improvement.
Facebook haven’t really released a ‘stable’ version of the SDK so you can’t rely on a particular version at the moment. Better to stick to the v3.x SDK for now in my opinion – at lease until Facebook stop changing the SDK so frequently.
How long does it take them to reach a stable release usually? Any guesses on when this might happen?
I have no idea. Since it’s open source and on github, it’s likely to change frequently. It’s really up to Facebook to mark a particular version as ‘stable’. Maybe posting a question on github will give you better information.
Good idea. I’ll try that.
Hi Niraj, I haven’t migrated to this new SDK version. I am still using the older one. I want to post to pages I administer as Page and not admin. I have solved that part. The other part is I want to make these posts without logging in. I already have my long-lived access tokens for the admin and the pages. I always get this error, ‘User session required’. How do I solve this problem?
There is already a tutorial on my site that covers this. I don’t write custom code, unless you want to pay for consultancy services.
Looks like they changed it yet again to 4.0.6. I’ve been messing with it for about 5 hours and I can’t seem to get it to work. Interested to see what you come up with. I used your exact code and it keeps going back to the login screen. The URL changes to include a code and state variable.
I’ve checked out the new version v4.0.6, and my sample code continues to work with it. You might have a configuration issue or the session isn’t saving correctly in your version.
Anyone know how to pass param to the query? Before you were able to.
Also, does anyone know when the old SDK will be deprecated?
Thanks!
You can pass parameters to the API just like before. Just include an array of parameters to the end of the FacebookRequest, as below:
The Graph API v1.0 will be deprecated in April 2015. After which, all v1.0 calls will automatically point to v2.0 calls.
I have been having the same problem for a while now with Facebooks new SDK. No problem going off and getting permissions but when redirecting to my page it does not exchange the pass code for an access token. Just sits there, no error and the session variable is null.
Do you get any errors? My code is designed not to show any exceptions, so try editing the
try...catch
statement to show any errors. It should give you a clue as to what’s going wrong.I tried to determine the exception generated but nothing comes out. Just get a null value set on the $session. In the process of trying out the JS API and seeing how that goes…
I am recieving this error,
Fatal error: Class ‘facebooksrcFacebookFacebookSession’
which is this line,
FacebookSession::setDefaultApplication( ‘foo’,’foo’ );
I had v-2 working but wanted to use
user_tagged_places permission,
Since the friends_ permissions is depreciated.
I followed your tutorial and I have been having problems getting it working after migrating to v-4.
I updated again today to 4.7 still get that error. I checked file paths etc. nothing helps.
Also when I try the old way with the new Facebook(array( this throws error now on new api level.
I read somewhere if you started your app before a certain date you have to use v-2 so I deleted my app and recreated from scratch.
Still same problem.
Any help would be appreciated. I cant get any help on stack…
For the sake of relaying information to anyone searching for help,
I tried doing this with composer as well as manually extracting the API.
Used autoload.php and took the required files route as in this tutorial.
What is the full error message? You’ve missed out the most important part of the error.
Hey, this is best FB php SDK 4.0.6 tutorial I ever found on internet. Facebook really sucks on the documentation of their php SDK. Your code is simple and just works!!
I wish I had known your blog since the beginning of facebook SDK. That would save me at least 8 more hours.
I Can’t express how grateful I am. Thank you!!
Hi Niraj,
Firstly thanks for the great article and kind replies.
I have the same problem, some of users mentioned above, that I get $session as NULL.
Clicking on login button correctly goes to my app on facebook, it asks for required permissions, gets back to my site, with URL changed by a long code appended, but not showing user details, instead it still shows Login button.
My PHP version is 5.4.9 I wrote print_r($ex) on different points (also on line 56) but nothing gets print. I turned on my error reporting too, but no advantage.
I used var_dump($session) on line 67, which says its NULL. then line 102 is executed.
Please help , i will be obliged.
Just set this up on a fresh server and I can’t get it to work properly. I set it up with my app id/secret/URL, see the login link, click it, log in, and then it redirects me back to the page with a new URL that has long “code” & “state” variables, but the page comes up blank.
Any ideas?
What version of PHP is the new server running? Do the
print_r
statements in thecatch
blocks return any errors that could point to an issue?This is an example of how BIG companies should speak to their customers. GRats on sharing this inf0 !
Niraj Shah, what is it good test folder?
In order that it serves the folder of test?
Not sure what you are asking for… The test folder is used to see if the SDK works as intended. It can be used to see which part of the SDK and/or API is broken. You should use it with tools like phpunit.
Hi Niraj, I mean that if I test folder is necessary to use it in my project? Thank you.
No, it’s not required. It’s an optional part of the API, normally used to make sure the API / SDK is working correctly.
Thanks for clearing the doubt.
Another question niraj, I register the domain and the site URL in Facebook, but throws me this message “This website has been identified as malicious and / or abusive.” What can I do in this case? thanks.
Hi Niraj, I have a question. When I add my domain and the URL of the site I get this message “This website has been identified as malicious and / or abusive.”?. Thank you.
You can try contacting Facebook and appeal the reason for blocking your domain. No guarantee that they will listen, but worth a try.
Hi Niraj, with this new version of the PHP SDK to version v4.0.8, does it change your code example?, Apart from the new subfolders. Thank you.
Only the files you include have changed with the new update. Please read Update #3. The remainder of the code work as normal.
Hey,
Thanks for the tutorial.
I’m having an issue migrating this particular snippet
[code language=”php”]
// previously
$facebook = new Facebook(array(
‘appId’ => ‘xxx’,
‘secret’ => ‘xxx’,
));
$accessToken = $facebook->getApplicationAccessToken();
$facebook->setAccessToken($accessToken);
$facebook->api($url, ‘POST’);
// v4.0
$session = FacebookFacebookSession::newAppSession(‘xxx’,’xxx’);
try {
$response = (new FacebookFacebookRequest(
$session, ‘POST’, $url
))->execute();
[/code]
And this is giving a: Uncaught exception ‘FacebookFacebookAuthorizationException’ with message ‘(#803) Some of the aliases you requested do not exist: v2.0557210865’
The issue is likely to be the $url, which you didn’t include in your code. What is it?
You’re correct, $url didn’t begin with a “/” (though this did work previously)
http://stackoverflow.com/questions/24071320/migrating-to-facebook-php-sdk-v4-open-graph/24071541#24071541
It’s likely that the previous API checked for a / in the URL and worked with or without it. Happy you have resolved the issue.
This does not allow the posting of the app on Facebook. How to achieve this feature
See this tutorial for an example of how to POST data to an API endpoint.
I’ve tried the whole Authentication with the FacebookJavaScriptLoginHelper() instead of the RedirectHelper. I added the JS SDK, the login works (the JS makes a request to /me and give all details), then there is a redirect to the page where I want to get this Session in php, and I get everytime this error: Uncaught exception ‘Facebook\FacebookAuthorizationException’ with message ‘This authorization code has expired.’ in …..\libraries\facebook\FacebookRequestException.php:104
JS Login: works
PHP Redirect Login: works
JS Login + PHP JS Login Helper: doesn’t work.
Does anyone have an Idea or can you create please an example?
Thanks and greetings, GodMod
You can only use the authorisation code once in the new SDK, so if you use it using JavaScript, you won’t be able to authenticate the user using PHP using the same code. To use both SDKs together, you will need the PHP version to read the cookie set by the JavaScript version.
Hi,
I used your code, but the problem appear when I install the Page tab and I try to Login inside facebook iframe. Nothing happens on “Login” button, but when I go directly to canvas URL then it redirect me on Facebook and autentification dialog box appear and everything is fine.
This code won’t work from Page / Canvas apps correctly. I’ll create a new tutorial to cover this shortly. You need to use the
FacebookCanvasLoginHelper
to on Canvas / Tab apps.Hi Niraj, and if I try it with localhost instead of a URL on the web, does this work?, Is to do as good evidence if I am implementing the code. Thank you.
localhost
should only be used if you’re developing code on your laptop / PC. It won’t work with a real app as Facebook does not allow localhost as a domain.Hi, I use v4.0.8 and I have a problem when I give the permission of using my fb-data the first time. Then it redirects to my site but the site doesn’t recognize the session or it recognizes a wrong session. Only after I destroy the session I can login and it works properly.
Maybe it’s not explicit enough for me but how do I get the actual access_token into a variable $access_token? I’m having a hard time seeing how it’s retrieved from the example for future use.
You can get the access token by calling
$access_token = $session->getToken()
once the user has logged in.this tutorial is really great. Thanks a lot for your time and sharing, you are helping a lot of us. However, I have a question. After couple of days working on it, I could manage to get my own informations from facebook, but after a clic on “logout”, generated by getLogoutUrl(), it’s now impossible for me to get my informations back. When I logout from my website / facebook, and I login again, i got only this session var : FBRLH_state, but nothing else, such as fb_token . Any suggestion ? …
my logout page on my website is made with $_SESSION = array();session_destroy();
Kindly
You need to see if any exceptions were found in the code. Add
print_r( $ex )
to thecatch( ... )
blocks to see what’s happening.As writed on your code, the print_r are here. I got couple of errors before, but i fixed all of them… And now, the code does not release any errors. It seems that my $session is empty. after checking my object $helper, i found out this :
[appId:Facebook\FacebookRedirectLoginHelper:private] => xxxx
[appSecret:Facebook\FacebookRedirectLoginHelper:private] => xxxx
[redirectUrl:Facebook\FacebookRedirectLoginHelper:private] => http://www.mywebsite.com/3/mon-compte
[sessionPrefix:Facebook\FacebookRedirectLoginHelper:private] => FBRLH_
[state:protected] =>
[checkForSessionStatus:protected] => 1
I’m using urlrewriting, I don’t think it could interfer with it ? …
Thanks a lot once again for your precious help
Ok, after few hours, I figured out my problem. The function getSessionFromRedirect was failing because of the scope “if($this->isValidRedirect())” was never triggered. Indeed ! my url rewriting was “hidding” the facebook’s GET variables. the redirrect was always false. I cured it creating a new page who deal with facebook’s get variables, then redirrect to the right page. A sort of middle page… Between my website and facebook.
Problem solved, hope my solution will help some pleople !
Rewrite rules always seem to cause issues. I’m glad you managed to resolve the issue.
dude i get this session every time and i dont even know where to find this session.Any idea where it is ?
Thanks a LOT for this example. the Facebook SDK Examples is really…. BAD!!
I use your example to start understanding. For those who want to test a bit more:
On line 99, you can add this:
Only with that, it will not work as the getLoginUrl Niraj put has ony the right to ask for the user to give us his info, but not to allow us to post. So we must change the getLoginUrl like this:
With that we can publish on the user page (publish_actions). Notice we ‘ask permissions” using the keyword ‘publish_actions’ and we “write” using the keyword ‘feed’ which is a bit confused.
I’m trying (without success, but with one or two liters of coffee…) to post on the page of our asso (ANSB.Brasil) in order to create an automatic news system. If I find how too, I’ll post this here, or maybe Niraj can help.
Thanks VERY VERY much!
Using permissions and publishing to endpoints is clearly documented on the Facebook Developer site. My code is just an example of what you can do. There are lots of other permissions that can be added to achieve different outcomes. Note that using the `publish_actions` needs approval from Facebook before it can be used by users.
Back. To post on a pages, you just need to replace the “me/” in the id of the page. Eg for our pages, as it’s on https://www.facebook.com/ANSB.Brasil this means the id is “ANSB.Brasil”.
So if I call :
$response = (new FacebookRequest(
$session, ‘POST’, ‘/ANSB.Brasil/feed’, array(
‘link’ => ‘www.ansb-brasil.org’,
‘message’ => ‘Troisème Test de message posté à partir de l’App FaceBook de l’ANSB’
)
I post on the page. Seems I post “as me” and not “as the page”. But I’ve still some coffee…
Follow this tutorial to see how to Post to Pages. In order to post as the page, you must use the page
access_token
, not the useraccess_token
. The tutorial needs to be updated to work with PHP SDK 4.0.x, but the method still remain valid.Hi Niraj,
Can the call to setDefaultApplication be avoided and setup the appId & appsecret in another place in order to set the two values local to a session instance instead of global?
Regards,
Mauro.
Many of the methods in the SDK let you pass in an app_id and secret as parameters, so you can override the default settings. You’ll have to look through the source code to see which methods support them.
I will see further. Thank you very much.
Thank man you are awesome !
I had a problems with checking if session exists, turned out that in my case the
if ( isset( $session ) ) {}
had to be changed to:
if ( $session ) {}
Hope that helps someone!
Thank you for this! I copied your exact code and put it in my app but I am having a problem. The ‘Logout’ option never shows even after successfully login. There is no catch Exception being thrown but the $session is retuning null. Have you seen such problems and how can I fix?
I’ve modified the code very slightly to deal with this issue, as it’s a common theme. Please see the change here:
https://gist.github.com/niraj-shah/ab1c74ad83df172e6075/revisions
Essentially, I’ve changed the first
IF...ELSE
statement into two separateIF
statements to deal with session errors, like expired sessions.Perfect. Works like a charm now! Quick question? Is it possible to make a tutorial such as this one:
http://www.codeofaninja.com/2011/06/display-facebook-photos-to-your-website.html
but with the up to date graph api instead of fql? I would like to get all images posted on my wall to be shown onto a page on my site. If you could do this, I will highly appreciate it and I am sure others will as well.
Thank you once again!