Facebook SDK 4.0.0 for PHP: A working sample to get started.

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:

  1. You have a working php hosting setup (no, I’m not covering this here).
  2. You have downloaded the SDK and uploaded the “Facebook” folder at the root of your project.
  3. You have an developer account at Facebook: https://developers.facebook.com/apps

Working code:

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>';
}

Debugging pointers:

As already explained, I had some issues, below are some I faced and how I eventually fixed them

  1. 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).
  2. 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’ );

     

  3. 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.

81 thoughts on “Facebook SDK 4.0.0 for PHP: A working sample to get started.”

      1. 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.

  1. 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

      1. 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…

  2. 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?

    1. 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…

      1. 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.

  3. 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.

      1. 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

  4. I get this error: Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /zzzzz/xxxxxx/public_html/ccccccc/Facebook/FacebookSession.php on line 89

  5. 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?

  6. After authurizing the application i get this

    Fatal error: Call to undefined function Facebook\mb_substr() in FacebookRequest.php on line 252

  7. 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

  8. the fuck error “Parse error: syntax error, unexpected T_OBJECT_OPERATOR in…” is because the SDK v4 requires PHP version 5.4

  9. 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.

    1. 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!!

  10. 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?

    1. 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

  11. 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?

  12. After a week of trying to use Facebook’s docs this worked straight away. Ironically, they suck at communicating. Thanks.

  13. 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?

  14. 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.

    1. 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.

    2. 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(‘…’);

  15. 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!

  16. 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.

  17. 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

  18. 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

  19. 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

  20. “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.

  21. 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

  22. 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’);

  23. 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

  24. 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

  25. 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.”

  26. 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

  27. 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 )

  28. 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

Thoughts?