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

By | September 24, 2014

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.



  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:


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)

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



Hopefully, you will be able to get your example working in a couple of minutes! Let me know otherwise.

21 Kudos

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

  1. Zakutira

    its do not work, i copy and paste this code in application index.php but when i open my application url it say nothing

    1. Ahmet Post author

      What do you mean by “it says nothing”? Do you not even see the login link?

      1. Andrew

        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.

      2. Andrew

        It actually fails after “require_once( ‘Facebook/FacebookSession.php’ );”

        1. Andrew

          Just realized my PHP was only 5.3. Upgraded to 5.5 and it worked.

  2. Magnus Burton

    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. Ahmet Post author

      Hey Magnus!
      Strange error. Are you just having above code on your file or did you made changes?

      1. Snuffish

        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…

  3. Sebastian

    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. Ahmet Post author

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

        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.

  4. Pingback: Facebook SDK 4.0.0 for PHP: A working sample to manage sessions | Ahmet Gyger's web log

  5. Albert

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

        it work’s fine but it could not show profile image

      2. Muhammad Zia ur rahman

        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.


  6. wil (@wil82448988)

    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…

  7. medoampir

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

  8. Damin

    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?

  9. medoampir

    After authurizing the application i get this

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

  10. Тихомир Соколов

    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,

  11. Jonas

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

  12. Nevzat

    Hi Ahmet,
    I’m tested your writing, working
    How to get user information and permissions

  13. Prateek

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

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

  14. Fernando Higashi

    I have an error:
    Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/noivasms/public_html/Facebook/FacebookSession.php on line 135

  15. deknyfgregoryGreg

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

      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

  16. Sumant Jha

    it works fine but it could not show profile image

  17. Jack

    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?

  18. Ted Eriksen

    Showing parse error to “use Facebook\FacebookSession;”

    How to fix this?

  19. anshuman

    i m a begginer & using localhost to test app….what should i gill in app domain & site url

  20. Pingback: Facebook SDK PHP v4 & CodeIgniter — working together!

  21. Paul

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

  22. gana

    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?

  23. Johnb21

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

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

      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;


      $session = new FacebookSession(‘…’);

  24. Shreyans Gandhi

    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(

    $response = $request->execute();
    $graphObject = $response->getGraphObject();


    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!

  25. Brad Wilson

    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.

  26. nikita

    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

  27. b0

    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

  29. Chris C. Russo

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

  30. rajmohan s

    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

  31. Angelo

    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:

    1. Ollie

      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.

  32. Soumik ROy

    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

  33. dkduyanh17

    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

  34. gergo

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

  35. Biran Maharjan

    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

  36. sahilkathuria

    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 )

  37. jamie

    thanks for this! Facebook couldn’t of been any more useless. you’ve saved a lot of people a lot of time 🙂

  38. Rajesh Ujade

    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


    If you are satisfied with the answer which I have given on stackoverflow. Please update here too.

  39. Pingback: Facebook Sessions and Facebook Tokens | Unsolved Software Issues

  40. Aidan Ayala

    Hi, this works fine for me however. Once logging in from facebook, the ‘$session’ varible is set to NULL. Any ideas?

  41. Wes

    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 )

  42. Santosh (@hihellobolo)

    This must work. Try this.





    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)

    // login helper with redirect_uri
    $helper = new FacebookRedirectLoginHelper( ‘http://localhost/fb/’ );

    try {
    $session = $helper-&gt;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-&gt;execute();
    // get response
    $graphObject = $response-&gt;getGraphObject();

    // print data
    echo print_r( $graphObject, 1 );
    } else {
    // show login url
    echo ‘&lt;a href=&quot;’ . $helper-&gt;getLoginUrl() . ‘&quot;&gt;Login&lt;/a&gt;’;


  43. Tim Marshall

    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=

  44. Redscouse

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

  45. Amit

    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

  46. Shubh Chintak

    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.

  47. Shubham Bajpai

    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

  48. Pingback: Facebook v4.4 PHP SDK 升級範例 - Tsung's Blog

  49. priya

    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.

  50. priya

    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

  51. Abir Das

    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

  52. Pingback: integrating Facebook SDK 4.xx with codeigniter, error with facebooksession class - BlogoSfera

  53. Pingback: integrating Facebook SDK 4.xx with codeigniter, error with facebooksession class | Solutions for enthusiast and professional programmers

  54. Pingback: Class 'FacebookSession' not found - Facebook PHP SDK v4 - BlogoSfera

  55. Larzon

    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.