I downloaded the new Facebook SDK 4.0.0, hoping to have a quick sample running. Instead, I had to scratch my head for nearly 1 hour before having a working sample. Not really a great experience (‘thanks’ Facebook for the great getting started document)!
Now at least I got it working, so I’m sharing some information below, as always, hoping to save you the time I just lost J.
Assumptions:
- You have a working php hosting setup (no, I’m not covering this here).
- You have downloaded the SDK and uploaded the “Facebook” folder at the root of your project.
- You have an developer account at Facebook: https://developers.facebook.com/apps
Working code:
[php]
session_start();
require_once( ‘Facebook/FacebookSession.php’ );
require_once( ‘Facebook/FacebookRedirectLoginHelper.php’ );
require_once( ‘Facebook/FacebookRequest.php’ );
require_once( ‘Facebook/FacebookResponse.php’ );
require_once( ‘Facebook/FacebookSDKException.php’ );
require_once( ‘Facebook/FacebookRequestException.php’ );
require_once( ‘Facebook/FacebookAuthorizationException.php’ );
require_once( ‘Facebook/GraphObject.php’ );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication(‘APPID’,’SECRET’);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( ‘http://www.metah.ch/’ );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo print_r( $graphObject, 1 );
} else {
// show login url
echo ‘<a href="’ . $helper->getLoginUrl() . ‘">Login</a>’;
}
[/php]
Debugging pointers:
As already explained, I had some issues, below are some I faced and how I eventually fixed them
- When using session_start(), I had a php warning:
Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at …/index.php:1) in …/index.php on line 2
To fix it use an editor that supported UTF-8 without BOM (Notepad++ encryption tab is useful). -
When calling the FacebookSession::setDefaultApplication I had an error:
Fatal error: Class ‘FacebookRedirectLoginHelper’ not found in …/index.php on line 28
This one is totally embarrassing (lame excuse: I haven’t used PHP for several years! And the solution is pretty straight forward, load the class first 🙂
require_once( ‘Facebook/FacebookSession.php’ ); - When clicking on the Login link, I had an OAuth error:
To fix it, simply go to your app setting (from your Facebook developer account) and correctly set your Site URL and App Domains.
Conclusion
Hopefully, you will be able to get your example working in a couple of minutes! Let me know otherwise.
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 do you mean by “it says nothing”? Do you not even see the login link?
It doesn’t work for me either. It just loads a blank page. I can echo text before index.php calls all those files, but I can’t echo text after calling them, so there is something going wrong with the require_once section at the top.
It actually fails after “require_once( ‘Facebook/FacebookSession.php’ );”
Just realized my PHP was only 5.3. Upgraded to 5.5 and it worked.
I still have the same problem with 5.5..
not working for me.. I only see the login link.(i m using hostgator to host my app and i hope this wont be a problem)
Hey! I’m getting the following error even though I’m dojng exactly as you are. I’m using Facebook’s PHP SDK version 4.0.0
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in */*/*/facebook/FacebookSession.php on line 89
Hey Magnus!
Strange error. Are you just having above code on your file or did you made changes?
I have the same error.. have struggling with this s*it for 6-7 hours now..
“Parse error: syntax error, unexpected T_OBJECT_OPERATOR in Facebook/FacebookSession.php on line 89”
Have modified the SDK to figure it out.. but it seems there only 1 thing that cause this issue. This entire facebook SDK is BROKEN…
use php >= 5.4
You are not using the correct PHP version. At least PHP 5.4 is required.
Ah, vepe Ndirash man? Muzeiiya.
That bugged my head earlier today too! It’s really a pain to get the old functionality back. I’m currently “fighting” to get the user’s email and it seems like a dead end. Also popup to ask for permissions is no longer available. Have you encountered this issues too?
Hi Sebastian,
you mean popup instead of redirection to Facebook OAuth?
Regarding the user’s email it indeed appear that it is not available anymore…
Hi there! Thank you for your reply.
Well, in previous version of PHP SDK if I’m not mistaking you had something like this :
$facebook = new Facebook(array(
‘appId’ => ‘YOUR APP ID’,
‘secret’ => ‘YOUR APP SECRET’
));
// get user UID
$fb_user_id = $facebook->getUser();
// get the url where to redirect the user
$location = “”. $facebook->getLoginUrl(array(‘scope’ => ‘publish_stream, email’));
Within ‘scope’ you had a list of “permissions” that you could ask the user to approve upon logging in to your application. Among them it was this email field, post on my behalf and more. Afterwards you could access it (email field) and used if needed.
Now, as far as I can see you cannot ask for that.
I still have to do some reading but I have a feeling that this version it’s limited compared to previous.
This tutorial shows how to ask for additional permissions, like email address, in the login link:
https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0/
work fine , thanks
It’s great help, thanks.
Super helpful, I forgot the requires as well! Honestly facebook should have those in their examples. Thanks – TM
Pingback: Facebook SDK 4.0.0 for PHP: A working sample to manage sessions | Ahmet Gyger's web log
I use your code but got this error: Parse error: syntax error, unexpected T_OBJECT_OPERATOR in Facebook\FacebookSession.php on line 93 , I did not change to PHP SDK files… how should I do.. need help.
You should download the sdk first: https://github.com/facebook/facebook-php-sdk-v4
it work’s fine but it could not show profile image
Dear Sir,
Hope you would be doing well, actually i am facing the issue with facebook-php-sdk-v4, i get login but after login nothing is happens only blank page comes
u can see this in this link http://dev.appcotech.com/fb_login/
please i need your kind guideline for this un-understandable error. waiting for your kind reply.
my email is below
Removed by Admin to protect you again spam.
Thanks,
Zia
I think that caused by low version of PHP. 4.0 SDK requires > 5.4.
I had same problem.
Use php > 5.4
I have no ideia.. This code works perfecly on my localhost, by when I submit to my online host “Session” don’t work properly..it goes to line 32 Exception…
I get this error: Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /zzzzz/xxxxxx/public_html/ccccccc/Facebook/FacebookSession.php on line 89
fucking awesome, thank you so much!!!
MUCHAS GRACIAS! funcionó.
Hi,
what should I do if I want to create canvas app but user doesn’t gives permissions to app yet? How to show LoginUrl etc?
After authurizing the application i get this
Fatal error: Call to undefined function Facebook\mb_substr() in FacebookRequest.php on line 252
hi,
same here .. Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /var/www/clients/client1/web1/web/session_test/Facebook/FacebookSession.php on line 93
I use PHP Version 5.3.10-1ubuntu3.11 & Nginx web server.
In last 5 days i detect some strange work in php sdk 3 .. now i want try sdk 4 .. but no luck 🙂
Best wishes,
Tihomir
You need PHP v5.4……….I was having same problem
the fuck error “Parse error: syntax error, unexpected T_OBJECT_OPERATOR in…” is because the SDK v4 requires PHP version 5.4
awsome, works! thx
Hi Ahmet,
I’m tested your writing, working
How to get user information and permissions
thanks
Hi there. I am very new to web development & I have a very basic question. Can i copy the above code to an index.php file and place it inside the FACEBOOK folder that was given in the SDK 4.0?
I am trying hard to understand, and i just feel like smashing my head on the ground.
Ok, 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!!
I have an error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/noivasms/public_html/Facebook/FacebookSession.php on line 135
Can you help about this: http://stackoverflow.com/questions/23753822/php-facebook-sdk-4-0-post-as-a-page-server-to-server
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?
This is great, but how do you log out just from the app, not facebook?
there is no way. according to facebook : “The function call will also log the person out of Facebook. The reason for this is that someone may have logged into your app and into Facebook during the login flow. If this is the case, they might not expect to still be logged into Facebook when they log out of your app. To avoid confusing people and to protect personal security, we enforce this logout behavior.”
source – https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.0
it works fine but it could not show profile image
This tutorial is now out of date. It doesn’t work with the latest version of the Facebook PHP SDK v4.0.5… The following tutorial still seems to work:
https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0/
THANK YOU. Thanks a lot. thanks thanks
I can’t seem to set the session or see the user graph object. For some reason it just displays a blank page. Any idea on why this might be?
Showing parse error to “use Facebook\FacebookSession;”
How to fix this?
i m a begginer & using localhost to test app….what should i gill in app domain & site url
it works great 😀 thanks!
Hi, it works fine on the example but I have integration troubles on anexisting website.
I get an error 500 from http://www.facebook.com/v2.0/dialogw hen I want to login )
Pingback: Facebook SDK PHP v4 & CodeIgniter — working together!
After a week of trying to use Facebook’s docs this worked straight away. Ironically, they suck at communicating. Thanks.
works fine. Thanks. But where i can get the user’s data? Can i get their username/email for reference? If i do, where i can view the user’s data?
Using all of those requires completely defeats the purpose of using namespacing. Use composer to install the facebook sdk and the facebook namespace will be added to the autoloader. Then there would be no need for all of those ugly require statements.
What about for people that don’t want to / cant use Composer? This at least helps them out. For everyone else, the Facebook documentation is sufficient.
I used xampp to install wamp, and composer and got the php sdk installed. I’m unable to initialize the sdk! It cannot find the FacebookSession class! Here’s my code:
require ‘C:\xampp\htdocs\vendor\facebook\phpsdkv4\src\Facebook\FacebookSession.php’;
use \xampp\htdocs\Vendor\facebook\phpsdkv4\src\Facebook\FacebookSession;
use \xampp\htdocs\Vendor\facebook\phpsdkv4\src\Facebook\FacebookRequest;
use \xampp\htdocs\Vendor\facebook\phpsdkv4\src\Facebook\GraphUser;
use \xampp\htdocs\Vendor\facebook\phpsdkv4\src\Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication(‘…’,’…’);
$session = new FacebookSession(‘…’);
I am trying to get the user profile image url using the FB PHP SDK v4.0.
Below is my code :
$session = new FacebookSession($access_token);
$request = new FacebookRequest(
$session,
‘GET’,
‘/me/picture?redirect=false’
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
print_r($graphObject);
On printing the $graphObject, below is the result :
“Facebook\GraphObject Object ( [backingData:protected] => stdClass Object ( [url] => https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/t1.0-1/c66.66.828.828/s50x50/534035_10200475956637071_664797794_n.jpg [is_silhouette] => ) ) ”
I want to extract the URL from this object. I tried everything but was unsuccessful.
I tried $graphObject->url , $graphObject->getProperty(‘url’) and many more. But no success.
Please help!
This tutorial doesn’t cover it, but you can convert the object to an array. See https://www.webniraj.com/2014/05/01/facebook-api-php-sdk-updated-to-v4-0-0/.
Change your code:
$graphObject = $response->getGraphObject();
to
$graphObject = $response->getGraphObject()->asArray();
And you’ll be able to extract the data as:
$graphObject[‘url’];
Thanks Ahmet,
your steps worked perfectly.
what is the result displayed?
i have tried. after i logged in, i redirected to the URL
i want to know where the echo print_r($graphObject,1) displayed?
thank you, great tutorial.
how can i get user profile on next page instead of same page
I just get a link which says Login….but doesn’t redirect.
oh hi, in my basic apps setting, there is no “website url” form, ony apps domain form, what should i do ?
I have the 4.0.8 sdk version.
I installed 2 days back using composer and using the autoload.php.
So I dont need the require files.
My problem is that the session isnt being stored.
it is redirected to the login page and says: Undefined variable: http_response_header in C:\wamp\www\facebook\vendor\facebook\php-sdk-v4\src\Facebook\HttpClients\FacebookStream.php on line 75
I am stuck. Please help
I did this and got the login link. What is this piece of code meant to do? Is it possible to get the user’s id (name) and display it on the page? It doesn’t show anything besides the login link, I thought it was going to display the user’s data too.. I’m confused. Please help. Thanks
Thanks for the tutorial it works great at first shot only . Can you please tell me at which line can I put a check whether the user “cancelled” rather than accepting the permission since the script redirects in loop presently . Thanks again for tutorial though
hei its really helpful..
“To fix it use an editor that supported UTF-8 without BOM (Notepad++ encryption tab is useful). ”
Encoding Tab my friend.
Thanks for the content, honestly the facebook documentation really sucks.
FacebookRedirectLoginHelper.php where this file in sdk. waste of time.
require_once(Facebook/FacebookRedirectLoginHelper.php): failed to open stream: No such file or directory in /home/tablytic/public_html/testforaccess/index.php on line 5
dont waste our time. give proper sdk
Hi,
Thanks so much for posting this, it helped me so much.
Anyways, I’d like to report a problem I had. Infact, I had to require some more files to get all working:
require_once(‘Facebook/Entities/AccessToken.php’);
require_once(‘Facebook\HttpClients\FacebookHttpable.php’);
require_once(‘Facebook\HttpClients\FacebookCurl.php’);
require_once(‘Facebook\HttpClients\FacebookCurlHttpClient.php’);
Same deal for me, I had to include the above files too. Maybe you add them to the code above.
Anyway, Ahmet, you are the man!
Your above guide finally got it working for me. The facebook dev docs were zero help.
I am getting this error:
Catchable fatal error: Argument 1 passed to Facebook\FacebookRequest::__construct() must be an instance of Facebook\FacebookSession, null given, called in D:\wamp\www\facebookapi\src\Facebook\FacebookRequest.php on line 318 and defined in D:\wamp\www\facebookapi\src\Facebook\FacebookRequest.php on line 182
Thanks for your starter guide, Ahmet! Here’s another resource that’s worth a mention:
http://www.benmarshall.me/facebook-sdk-php-v4/
it is working fine
I faced all problems in your posting, thank you fro your help. I also had small problem that I couldn’t get username from facebook. Please show how to get username from php sdk v4
Thank you, very useful.
Note: if you see the error described in the 3rd debugging pointer, it might be because of incorrect app id or password, not only because of incorrect domain name setting as the error message claims:
“Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.”
Thanks! A great help.
I have copied the codes that you had provided and changed my appid and app secret.
Now I am able to see Login (I am already logged in facebook with my username) in my app but can’t able to get userid. I am confused how to get pass from here.
Also I am now aware how this FacebookRedirectLoginHelper() actually works.
Thanks in advance
Not Sure, if issue is from my side.
but i am not getting session value. At the end of the code i am printing session variable and it return below.
( [FBRLH_state] => 6dd8c66ac343eacd0b43661b09bcaea6 )
thanks for this! Facebook couldn’t of been any more useless. you’ve saved a lot of people a lot of time 🙂
Hey Buddy,
I have seen most of the people uses your solution on statckoverflow.com. I have some questions as below-
1. Why do you use require_once?
2. If you use require_once then you dont have to use `use` statement in your code.
3. Facebook are using Implementations of PSR-4.
4. You just need autoload.php to register classes in php. It will load class dnyamically. Its just need packagename i.e. namespace and class filename.
I have given detail answer on stackoverflow.com. Please check this link
http://stackoverflow.com/questions/23569934/error-class-facebook-facebooksession-not-found-with-the-facebook-php-sdk/25720111#25720111
If you are satisfied with the answer which I have given on stackoverflow. Please update here too.
Thanks,
Rajesh
Pingback: Facebook Sessions and Facebook Tokens | Unsolved Software Issues
The paths have changed it should be “Facebook/src/Facebook”
Hi, this works fine for me however. Once logging in from facebook, the ‘$session’ varible is set to NULL. Any ideas?
Hi, I have the exact same code but am unable to get the url from the array and get the below notice. It seems the array I get looks a little different than Shreyans as it does not say => stdClass Object.
Any advice very much appreciated!
Notice: Trying to get property of non-object in /xxx/xxx/fblogin.php on line 67
Array ( [is_silhouette] => [url] => https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p200x200/1016554_10153735860935156_352883157_n.jpg?oh=7f9ad20c9e509e66f2cc6540e62d1b04&oe=5545860A&__gda__=1426650154_69daf8e31501378bacec2e2e94e9ba99 )
This must work. Try this.
[code]
<?php
session_start();
require_once(‘Facebook/HttpClients/FacebookHttpable.php’);
require_once(‘Facebook/HttpClients/FacebookCurl.php’);
require_once(‘Facebook/HttpClients/FacebookCurlHttpClient.php’);
require_once(‘Facebook/FacebookSession.php’);
require_once(‘Facebook/FacebookRedirectLoginHelper.php’);
require_once(‘Facebook/FacebookRequest.php’);
require_once(‘Facebook/FacebookResponse.php’);
require_once(‘Facebook/FacebookSDKException.php’);
require_once(‘Facebook/FacebookRequestException.php’);
require_once(‘Facebook/FacebookOtherException.php’);
require_once(‘Facebook/FacebookAuthorizationException.php’);
require_once(‘Facebook/GraphObject.php’);
require_once(‘Facebook/GraphSessionInfo.php’);
require_once(‘Facebook/GraphUser.php’);
require_once(‘Facebook/Entities/AccessToken.php’);
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
use Facebook\GraphUser;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication(‘303679886495218′,’0a3fbc6e7b665b75249083cbb352c0d1’);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( ‘http://localhost/fb/’ );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo print_r( $graphObject, 1 );
} else {
// show login url
echo ‘<a href="’ . $helper->getLoginUrl() . ‘">Login</a>’;
}
[/code]
great, It works perfectly.
How can i post on Facebook wall from my website?
Okay so I’ve uploaded your documents, my login and facebook folder are located at domain/Desktop/ and I have set my redirect URL to desktop/confirmation.php however upon clicking to login it sends me to this page with a long URL string starting with; confirmed.php?code=
Dude!! I spent around 3 hours last night trying to get this basic piece of code working. Got up this morning, a quick google search brought me here. 10 mins later I’m up and running!!
Cheers fella, you’re a superstar!!
the code works fine on the xampp server but when i uploads my php file to the server the it gives error for my code as:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR
And it gives error at this line:
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION[‘fb_token’] = $session->getToken();
// and create a new Facebook session using the
cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
// for getting timeline album id
$user_profile = (new FacebookRequest($session,
‘GET’, ‘/me/albums’))->execute()->getGraphObject();
$album = $user_profile->getProperty(‘data’);
Please help me soon,Thaanx
THANKS!
This was a big help to me.
Well Bro I am getting the following problem:
Fatal error: Uncaught exception ‘Facebook\FacebookSDKException’ with message ‘error setting certificate verify locations: CAfile: /home/technosago/public_html/Facebook/certs/DigiCertHighAssuranceEVRootCA.pem CApath: none’ in /home/technosago/public_html/Facebook/FacebookCurlHttpClient.php:150 Stack trace: #0 /home/technosago/public_html/Facebook/FacebookRequest.php(260): Facebook\FacebookCurlHttpClient->send(‘https://graph.f…’, ‘GET’, Array) #1 /home/technosago/public_html/index.php(64): Facebook\FacebookRequest->execute() #2 {main} thrown in /home/technosago/public_html/Facebook/FacebookCurlHttpClient.php on line 150
What to do????????????? Kindly help me out.
what will be the website name and app domain for the localhost in xampp
I have filled this for which it is not accepting
$helper = new FacebookRedirectLoginHelper(‘C:\xampp\htdocs\xampp\project\Homepage\Homepage.html’);
The file is my homepage from where I m accessing fbconfig.php
Pingback: Facebook v4.4 PHP SDK 升級範例 - Tsung's Blog
Thanks its working fine for me.
i have use this code so it is showing this syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in /home/myloanca/public_html/freescale/test.php on line 15. how to solve this error.
how to solve this error syntax error, unexpected T_STRING in /home/myloanca/public_html/freescale/facebook-php-sdk-v4-4.0-dev/src/Facebook/FacebookSession.php on line 24
Hi, thanks for the nice tutorial, And I follow your website every time
I just found a video that are related to the same topic. They are using some other techniques and less codes, can you tell me is it secure. ? It will really help me.
Here is the video
————————-
Pingback: integrating Facebook SDK 4.xx with codeigniter, error with facebooksession class - BlogoSfera
Pingback: integrating Facebook SDK 4.xx with codeigniter, error with facebooksession class | Solutions for enthusiast and professional programmers
Pingback: Class 'FacebookSession' not found - Facebook PHP SDK v4 - BlogoSfera
Great article. Can you explain what this is doing though? “http://www.metah.ch/” … I plug in my web link and nothing … put your link in it works. so you’re missing to explain an important piece of the puzzle here. Also I’d appreciate if you can include piece of the code that gets users first, last names… Thanks a bunch.
It does not work.
This was great. I don’t suppose you have a version for the SDK v5 do you? I have almost no hair left(!)