Web Niraj
  • Facebook
  • Flickr
  • Github
  • Linkedin
  • Twitter
  • YouTube
Online portfolio, code examples and developer blog
  • About
  • Contact
  • Portfolio
  • WordPress
Search the site...
  • Home
  • Blog
  • Facebook API: PHP SDK Updated to v4.0.0

Facebook API: PHP SDK Updated to v4.0.0

291

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.

Facebook, Facebook Graph API, Facebook PHP SDK 4.0, PHP

291 comments on “Facebook API: PHP SDK Updated to v4.0.0”

  1. dan says:
    June 28, 2014 at 4:55 AM

    Hi Niraj Shah,
    Thank you so much for the article,

    I’am integrate version 4.0.9 into my site.
    You could help me how to show popup log in.
    Currently, When click log in, it auto redirect to facebook site.
    Thanks you so much.
    Dan.

    Reply
    • Niraj Shah says:
      June 28, 2014 at 6:35 PM

      The Facebook PHP SDK uses a full-page login. You need to use the JavaScript SDK if you want a login popup.

      Reply
      • dan says:
        July 7, 2014 at 8:11 AM

        Thank you.
        I’ve just fixed by use JavaScript SDK.
        thank again.
        Dan.

    • EE says:
      August 19, 2014 at 8:58 PM

      I added ‘&display=popup’ at the end of the getLoginUrl and it changed the display mode to popup

      Reply
  2. anandan says:
    June 28, 2014 at 1:25 PM

    i got blank page using this code please help me
    validate() ) {
    $session = null;
    }
    } catch ( Exception $e ) {
    // catch any exceptions
    $session = null;
    }
    }

    if ( !isset( $session ) || $session === null ) {
    // no session exists
    try {
    $session = $helper->getSessionFromRedirect();
    } catch( FacebookRequestException $ex ) {
    // When Facebook returns an error
    // handle this better in production code
    print_r( $ex );
    } catch( Exception $ex ) {
    // When validation fails or other local issues
    // handle this better in production code
    print_r( $ex );
    }
    }

    // see if we have a session
    if ( isset( $session ) ) {
    // save the session
    $_SESSION[‘fb_token’] = $session->getToken();
    // create a session using saved token or the new one we generated at login
    $session = new FacebookSession( $session->getToken() );
    // graph api request for user data
    $request = new FacebookRequest( $session, ‘GET’, ‘/me’ );
    $response = $request->execute();
    // get response
    $graphObject = $response->getGraphObject()->asArray();
    // print profile data
    echo ” . print_r( $graphObject, 1 ) . ”;
    // print logout url using session and redirect_uri (logout.php page should destroy the session)
    echo ‘<a href=”‘ . getLogoutUrl( $session, ” ) . ‘”>Logout</a>’;
    } else {
    // show login url
    echo ‘<a href=”‘ . getLoginUrl( array( ’email’, ‘user_friends’ ) ) . ‘”>Login</a>’;
    } ?>

    Reply
    • Niraj Shah says:
      June 28, 2014 at 6:37 PM

      You clearly haven’t copied my sample code correctly. You probably have a few PHP errors in there causing a blank page. Enable error output and fix the errors.

      Reply
      • anandan says:
        July 1, 2014 at 5:32 AM

        how to enable errors in heroku

      • Niraj Shah says:
        July 1, 2014 at 12:19 PM

        The same way you enable errors in PHP:

        error_reporting(E_ALL);
        ini_set('display_errors', 1);

      • Gaurav says:
        July 3, 2014 at 5:04 PM

        I just get a Login link and nothing happens when I click on it. I am new to FB development. Can you help me? I am trying to create a Canvas app.

    • shradha says:
      September 25, 2014 at 6:00 AM

      sir i copied ur code but the problem comes in it that once i logged in and then logout it still shows the logout link and my profile data instead of showing login link ..

      Reply
      • Niraj Shah says:
        September 25, 2014 at 9:55 AM

        Are you destroying the session and deleting cookies on the logout page? If you don’t clear the session, the user will still appear logged in until the session expires.

  3. tudor says:
    June 28, 2014 at 3:46 PM

    you really made my day,
    Thanks a lot, facebook official tutorial sucks

    Reply
  4. nikita says:
    July 2, 2014 at 4:40 PM

    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

    Reply
    • Niraj Shah says:
      July 2, 2014 at 4:51 PM

      What version of PHP are you using? Also, what code are you using to call the API. This error would occur if you’re trying to access a page that’s restricted or not found.

      Reply
  5. b0b0123 says:
    July 10, 2014 at 10:40 AM

    Hello. I am a novice at coding. Currently trying to create a facebook app. I followed your tutorial and I managed to get the login and then the pop up box that asks for permission. But after clicking okay, nothing happens – shows the broken page with the sad face. When refreshed, the pop up box no longer appears. No user details are shown either. I am so confused. Can anyone help me out? Thanks.

    Reply
    • Niraj Shah says:
      July 15, 2014 at 3:47 PM

      Once the user has authorized your app, they will never see the login popup again (unless you change the scope of permissions). Are you using the most recent code I’ve posted, as it includes fixes for the blank page issue. Also, make sure you’ve updated any URLs I’ve used in my code to match your setup. It’s likely that my sites.local URL is causing a problem on your setup.

      Reply
      • b0b0123 says:
        July 16, 2014 at 9:23 AM

        Thank you so much for replying… I am not too sure but I think it’s because I am using localhost and facebook doesn’t like that – requires a security certificate. I tried to create my own self signed one using openssl within xampp but it doesn’t seem to load anything either. Do you have any idea how to use localhost to implement a facebook app? I would really appreciate any help or advice. I feel so lost – blindly trying to solve it. (Not even sure if it’s meant to be this complicated or am I just stupid)… thanks again.

      • Niraj Shah says:
        July 16, 2014 at 11:04 AM

        Facebook used to allow developers to test apps without SSL, but now it’s forced. You’ll have to setup a self-signed certificate to test locally, or code on a server with a valid SSL certificate. I use MAMP on Mac, with a self-signed certificate to develop locally.

      • b0b0123 says:
        July 16, 2014 at 11:14 AM

        IT FINALLY SHOWS SOMETHING. THE DATA RETRIEVED ON THE PAGE! Does that mean I have combated the ssl problem? 😀

      • b0b0123 says:
        July 16, 2014 at 10:55 AM

        I have just redone it all again. Copied your code. For the redirect link so I put the facebook url? https://apps.facebook.com/myapp

        I get this error now: Fatal error: Class ‘Facebook\FacebookServerException’ not found in C:\xampp\htdocs\app\Facebook\FacebookRequestException.php on line 110

        How do I know which facebook files to include, there is so many? I copied your code..

        Thank you!

      • Niraj Shah says:
        July 16, 2014 at 11:08 AM

        Include the following below the FacebookSDKException line:

        ...
        require_once( 'Facebook/FacebookSDKException.php' );
        require_once( 'Facebook/FacebookRequestException.php' );
        require_once( 'Facebook/FacebookServerException.php' );
        ...
        

        Then further down, add:

        ...
        use Facebook\FacebookSDKException;
        use Facebook\FacebookRequestException;
        use Facebook\FacebookServerException;
        ...
        

  6. b0b0123 says:
    July 16, 2014 at 3:03 PM

    Thank you so much! I think it’s finally working now, data echoes onto the page, woo!

    Can I ask about the logout.php, how do we log out the user?

    Thanks!

    Reply
    • Niraj Shah says:
      July 16, 2014 at 5:09 PM

      logout.php should contain code to destroy the session and a redirect back to your app / site:

      
      

      Reply
  7. mssb says:
    July 19, 2014 at 6:07 PM

    I had following error :: PHP Fatal error: Class ‘Facebook\\Entities\\AccessToken’ not found in /home/madawa/Desktop/F/Facebook/FacebookSession.php on line 74, referer: http://localhost/F/Test.php

    Reply
    • Niraj Shah says:
      July 20, 2014 at 11:11 AM

      Use the code from Update #3 to fix the issue.

      Reply
  8. mwsasser says:
    July 20, 2014 at 1:44 PM

    Looks like they are up to 4.0.9, I wonder how much further they will go?

    Reply
    • Niraj Shah says:
      July 20, 2014 at 3:31 PM

      They are currently working on v4.1, which is probably still a few weeks away from release. The SDK is undergoing major changes, so this tutorial is pretty much be useless when v4.1 comes out.

      Reply
      • mwsasser says:
        July 20, 2014 at 8:10 PM

        Actually it’s been a good learning experience. Ironically we’ll all have to wipe out what we’ve done but thats part of the process. Hopefully it’ll be worth it in the end.

  9. Julian says:
    July 20, 2014 at 4:21 PM

    I just wanted to say,…. THANKYOU SO MUCH!

    Reply
  10. Hannes says:
    July 20, 2014 at 10:20 PM

    Hello,

    When I open your example then it shows a Login link. I can then sign into facebook, but then afterwards I am redirected to an empty page on localhost showing the start page of my xampp server. Any idea what I have done wrong?

    Reply
    • Niraj Shah says:
      July 21, 2014 at 10:52 AM

      Check the redirect URLs you are using in your code. Make sure they are valid and pointing to the correct code on your server. It’s probably one URL that you’ve forgot to change somewhere in the code.

      Reply
  11. ananth says:
    July 21, 2014 at 12:40 PM

    Fatal error: Call to undefined function Facebook\Entities\mb_strlen() in …../Facebook/Entities/SignedRequest.php on line 301

    I got this error please give me solution….

    Reply
    • Niraj Shah says:
      July 21, 2014 at 10:03 PM

      Looks like the mb_strlen() function isn’t installed on your version of PHP. See the PHP Manual for information on how to install it.

      Reply
  12. Dewi Lestari says:
    July 22, 2014 at 11:27 AM

    I just learn this SDK, want to make some piece of script in my Apps. Thank you for this tutorial.

    Reply
  13. Lisa Johnson says:
    July 25, 2014 at 3:13 PM

    Hi all,

    If I have the username/password of the user that uses the app, can I do the login process autmatically?

    Reply
    • Niraj Shah says:
      July 25, 2014 at 4:20 PM

      No, Facebook only supports OAuth authentication for the API. There are some instances where this is allowed (i.e. PlayStation Network) but it’s not available to the general public. You should not collect usernames / passwords of users, except your own.

      Reply
  14. mwsasser says:
    July 30, 2014 at 3:03 PM

    So it looks like the older 4.x.x SDKs could be shut off in December. When I visit https://developers.facebook.com/ there is a notice that says:

    “Graph API v2.0 and the new Facebook Login. Upgrade your apps before December 25 to protect 90% of your users’ experiences.”

    Reply
    • Niraj Shah says:
      July 30, 2014 at 10:22 PM

      This is just a precaution and only affects apps that still use the v1.0 Graph API. You can continue to use the older SDKs (PHP v3.x) until April 30th 2015, and even longer as long they use Graph API v2.0.

      The PHP SDK 4.x is not affected as it already uses Graph API v2.0, but PHP SDK 4.1+ will include new features going forward.

      Reply
  15. RahulG says:
    August 2, 2014 at 1:35 PM

    is giving PHP Fatal error: Class ‘Facebook\Entities\AccessToken
    show how to solve this issue .

    Reply
    • Niraj Shah says:
      August 2, 2014 at 1:37 PM

      Read all the updates at the bottom of the post for updated code.

      Reply
  16. Parse.com: Using the Official Parse PHP SDK (v1.0.x) | Web Niraj says:
    August 5, 2014 at 8:51 PM

    […] has released an official PHP SDK, similar to the Facebook PHP SDK 4.0. As usual, it’s not very well documented and you may have to jump between different […]

    Reply
  17. b0b0123 says:
    August 11, 2014 at 3:15 PM

    When you load the page, is it meant to show the login URL even when you are already logged in on facebook? I also get this error: Catchable fatal error: Argument 1 passed to Facebook\FacebookRequest::__construct() must be an instance of Facebook\FacebookSession, null given, called in.. kinda confused now that I have different scripts.. I have one script (getfriend.php) that includes all your code above and get friend request. Then another script that holds the html of the page which includes the other script… I have other scripts too that includes “getfriend.php”… I have the html in a different script because I don’t want this to be repeated in other scripts :S

    Reply
    • Niraj Shah says:
      August 11, 2014 at 3:20 PM

      The login link will only be shown if the session does not already exist and a logged-in user isn’t detected from the session. Depending on your PHP Session settings, this is usually after a hour. The error you’re getting suggests you are trying to pass in an invalid session to the FacebookRequest class, which suggests that the user isn’t logged in.

      Reply
      • b0b0123 says:
        August 11, 2014 at 3:45 PM

        I think I know why I am getting the error… but not sure how to correct it. Hard to come up with a good design for your code. Too much going on, kinda confusing. hmm. Is possible to do direct to another page when user has clicked on the login URL? Would I use header for this?

  18. b0b0123 says:
    August 11, 2014 at 4:19 PM

    I think I’ve fixed it using header and adding another script! So I don’t include the script that makes the api request in index until I have got the session… so I don’t get the error. 🙂 think it works. 🙂 thanks!

    Reply
  19. b0b0123 says:
    August 11, 2014 at 5:35 PM

    What I don’t understand is, it works fine on my localhost url but when it is loading from the facebook canvas, the buttons isn’t responsive – nothing works. Do you have any idea why this is the case?

    Reply
    • Niraj Shah says:
      August 11, 2014 at 7:48 PM

      Add target=”_top” to the login link for Canvas Apps. Facebook doesn’t allow navigation of other FB paves via iFrame.

      Reply
      • b0b0123 says:
        August 12, 2014 at 2:32 PM

        I think it worked before…. and my notification link, the buttons work and directs me to another page..

        Do you mean, like this?:

        } else {
        // show login url
        echo ‘getLoginUrl( array( ’email’, ‘user_friends’, ‘publish_actions’, ‘publish_stream’, ‘manage_friendlists’, ‘user_photos’, ‘read_friendlists’ ) ) . ‘”>Login’; //get permissions
        }

        I get the error that the requested URL is not found.. my redirect url is the canvas URL…

        // login helper with redirect_uri
        $helper = new FacebookRedirectLoginHelper( ‘https://apps.facebook.com/myapp’ );

      • Niraj Shah says:
        August 13, 2014 at 6:24 PM

        Your code appears garbled. Try wrapping your code in <code> tags next time.

  20. b0b0123 says:
    August 12, 2014 at 4:29 PM

    I think the problem is with the browser? It has a warning sign saying it’s not secure as it contains images when I click the submit. So when I disable the blocking, it seems to work again.

    Reply
    • Niraj Shah says:
      August 13, 2014 at 6:20 PM

      This is probably caused by your code including images or CSS / JS files over a non-SSL / HTTPS connection. Make sure any files your reference are loaded using HTTPS.

      Reply
      • b0b0123 says:
        August 14, 2014 at 10:50 AM

        Kinda confused. I don’t actually have any images or CSS/JS files. Just the multi part form to upload a photo onto the server.. also, I have a SSL connection? (I created the self signed certificate??) otherwise, the page wouldn’t load at all on facebook… (right? Sorry, not even sure)

        Also, have you tried out the privacy parameter when posting? I have been stuck on this for 2 weeks, and cannot seem to find anyone who has been stuck on the same thing to find an answer. Do you think you could have a look at my sof question?
        http://stackoverflow.com/questions/25084519/facebook-api-php-setting-privacy-of-photo-post-to-custom-but-shows-only-me-i

        Friend id – I got from GET /me/friends – which is the unique user id of those who have accepted my app. I have tried both deny and allow but whatever user id I put, it just result in “only me”. I have put “ALL_FRIENDS” for allow and it works – just id not working! I must be missing something stupid again or has this somehow been changed/deprecated by facebook? 🙁 sorry for such a long post.

  21. Sebastian says:
    August 18, 2014 at 9:26 AM

    First of all, this is a very good tutorial, but i have a question. When I click Login from the index.php , it redirects me to facebook to enter my user and password, then it shows me the data it fetches. So far, so good, but when clicking Logout, it doesn’t destroy the session and redirects the user to the index and still show the data, not the login button. Can you tell what should I do? For the logout.php I used your code from the comments.

    Reply
    • Niraj Shah says:
      August 18, 2014 at 10:27 AM

      Do you have session_destroy(); in your logout.php script? That’s the most important like to delete the user’s sessions.

      Reply
      • Sebastian says:
        August 18, 2014 at 10:44 AM

        I click Logout, it goes to logout.php, then I redirects to index.php where I have the Login button and nothing more, but instead of showing me Login button, it shows me the facebook data with the Logout button.

    • Brian says:
      August 19, 2014 at 8:48 AM

      I too had this problem – my logout page redirected to my app, which showed all the user profile data. It looks like you also have to delete the cookies and any globals associated with the Session. See here for code that worked great:
      http://php.net/manual/en/function.session-destroy.php

      Reply
      • Sebastian says:
        August 19, 2014 at 1:01 PM

        Thanks a lot Brian, it worked. 🙂 Also, thanks to Niraj Shah for the tutorial.

  22. Brian says:
    August 19, 2014 at 12:40 AM

    I just wanted to say that this tutorial was Massively helplful, after a weekend of banging my head against the wall trying to get login to work, when so many web pages are written for older versions of the SDK. Kudos to you for good, current, working code!

    Reply
  23. John says:
    August 19, 2014 at 12:09 PM

    I have a script that retrieved the picture from posts. now the picture field is not there since a few days back!? Do you know how to get a picture in a post in some news feed?

    Reply
    • Niraj Shah says:
      August 19, 2014 at 1:07 PM

      Must be a bug, but it appears to work for me. Try searching for any related bugs that may have been reported.

      Reply
      • John says:
        August 19, 2014 at 8:10 PM

        Which group did u test in? If I check in the Graph API Explorer,

        groupId/feed

        i see all posts. And just a few days ago, it was a picture field, in the posts that had a picture. Now I only see this field in shared posts.

      • Niraj Shah says:
        August 20, 2014 at 2:45 PM

        Yes, it looks like it’s no longer working. It must be a bug with Facebook.

      • John says:
        August 19, 2014 at 10:16 PM

        I found bugreports on it, as you hinted.

        https://developers.facebook.com/bugs

        Its a fix already on

        https://graph.beta.facebook.com/

        That works. Thanks for pointing this out. FB have quite a good bug reporting tool here.

  24. itzkelzera says:
    August 20, 2014 at 8:08 PM

    I was looking to some codes for managing the session; and this is working like a charm. Keep up the good work.

    Reply
  25. Tarun Narula says:
    September 9, 2014 at 12:25 PM

    sir, how to make if else statement on condition by which notification to fb friend is successfully gone or not..?

    Reply
  26. Federico says:
    September 10, 2014 at 10:04 PM

    I was having the error “Session has expired, or is not valid for this app” and it was because I change ” array( ’email’, ‘user_friends’ ) ” to ” array( ‘public_profile’ ) “. Avoid doing that, public_profile in the new sdk is always asked by default, if you only want that and no other permission just use “array()”.

    Reply
  27. Ady says:
    September 25, 2014 at 7:49 AM

    Hello. It’s possible to make a facebook comment box like this https://developers.facebook.com/docs/plugins/comments/ in php?

    I didn’t find anything about it on facebook tutorials.

    Reply
    • Niraj Shah says:
      September 25, 2014 at 9:53 AM

      Yes it is possible to replicate this functionality in PHP but it’s a waste of time. You won’t find any tutorials on it because it’s easier to just use the plugin or something like disqus instead of trying to re-invent the wheel.

      Reply
      • Ady says:
        September 25, 2014 at 11:58 AM

        I want to sort that facebook comments by likes. And i was thinking that it’s possible if only i make in php that comment box. I’m beginner and i’m still learning. Can you help me with some advices?

      • Niraj Shah says:
        September 29, 2014 at 10:16 AM

        Even with PHP, it will be difficult to achieve this as the API does not support sorting. I am unable to provide specific help as this is a complicated process, but I do offer paid consulting services.

  28. yasir says:
    October 11, 2014 at 11:38 AM

    Awesome tutorial…… but 1 issue is that when i click on logout button session is not destroyed. I also destroy session in logout page but nothing happens. Any help?

    Reply
    • Niraj Shah says:
      October 20, 2014 at 8:21 PM

      Is the user logged out of Facebook successfully?

      Reply
      • yasir says:
        October 24, 2014 at 9:04 AM

        No, user can’t logged out of facebook…… i also destroy session on logout page.

      • Niraj Shah says:
        October 24, 2014 at 11:41 AM

        Not sure what could be going wrong then. If the correct session is used in the logout API call, the user should be logged out of Facebook. Then it’s your responsibility to delete the cookie / session and log them out if your App.

      • yasir says:
        October 27, 2014 at 6:46 AM

        Thanks for your rply…… I will be very thankful to you if u help me in log out code. This is my code

      • Niraj Shah says:
        October 27, 2014 at 11:36 AM

        I’ve added the code used in my logout page in the main article.

      • yasir says:
        October 27, 2014 at 3:25 PM

        Thanks for your reply…… one more issue is that your logout line which redirects to logout.php didn’t work correctly. When i click on the logout link it redirects to facebook home page. I also edit my log out url on that page but it redirects to facebook home page.

  29. Ramon says:
    October 14, 2014 at 4:52 PM

    Hi,
    I did everything but I got white screen. 🙁
    please help.

    Reply
    • Niraj Shah says:
      October 17, 2014 at 11:48 AM

      Double check your app settings on Facebook and make sure you are using the correct App ID and Secret in your app. Add some debug code to your app to see if any Exceptions are thrown anywhere that could be causing a blank page.

      Reply
  30. premkumar says:
    October 18, 2014 at 6:22 AM

    Hi Niraj,

    Need to integrate facebook php sdk 4.0 in my local. I have used basic example from this site and implemented in local. I can able to view my login user detail, but when i am trying to get user friends, it is not fetching the friends content. it only displaying total count.

    $request = new FacebookRequest( $session, ‘GET’, ‘/me/friends’ );

    Please guide me to resolve this issue..

    Thanks..

    Reply
    • Niraj Shah says:
      October 19, 2014 at 11:40 AM

      In order to get friends information, you must ask for the user_friends permission. This new permission only allows you to see mutual friends that also use your application. You can no longer see the entire friends list unless you use the taggable_friends API.

      Reply
  31. GOPAL G says:
    October 26, 2014 at 7:40 AM

    Hi,

    I am using the below code to authenticate the user with facebook login app: i have a problem the code below is working fine under certain scenarios.

    a) User A Logs in with fb account works fine – > logs out ->works fine
    b) return to login page after USER A is logged out
    c) USER B logs in with second account the graph returns the USER A’s Details instead of the USER B
    d) if we open the facebook on the next tab logged in user is USER A.

    Im not sure where i am going wrong or if it is the SDK acting crazy!.

    Reply
    • Niraj Shah says:
      October 27, 2014 at 11:30 AM

      When you log the user out of Facebook, you also need to make sure you clear the session for that user in your code. Otherwise, the access token is stored in the app, and a second user logging in will inherit the first user’s session. Use session_destroy() or equivalent to clear the session.

      Reply
  32. Atiq Samtia says:
    November 2, 2014 at 11:44 AM

    Hey Niraj,

    I am wandering how to get the list of all the friends of the authenticated user and groups he joined ?

    kindly reply me soon..

    thanks

    Reply
    • Niraj Shah says:
      November 3, 2014 at 10:27 AM

      To get Friends, please see this tutorial. For groups, you’ll need to ask the user for the user_groups permissions and make a API call to /me/groups.

      Reply
  33. Lucky Evelyne says:
    November 3, 2014 at 5:27 PM

    The script works fine and it’s the most complete, useful version that I’ve found (and, as far as I could find, the only one that truly works with php sessions). However, my problem is that when I click Logout, it logs me out of FACEBOOK, not just the app itself. Is that normal? I would expect to logout of the app, not off of facebook…

    Reply
    • Niraj Shah says:
      November 3, 2014 at 5:48 PM

      Yes, making a API call to the logout method in the Facebook SDK logs the user out of Facebook. To log the user out of your application, you must delete the cookies / session related to that user. I’ve included code for my logout.php page at the end of the article.

      Reply
  34. Tatsuya says:
    November 10, 2014 at 1:21 PM

    Hi,mister Niraj.
    I’m now trying to using Facebook php sdk 4.0 to retrieve datas of my facebook acount.

    I tried , but php always says (apache error log) class SDKException not found and session is not active.

    Here are source codes of two files(call , and callback pages)

    call.php

    <?php
    session_start();
    require("vendor/autoload.php");
    use FacebookFacebookRequest;
    use FacebookGraphUser;
    use FacebookFacebookRequestException;
    use FacebookFacebookCanvasLoginHelper;
    use FacebookFacebookRedirectLoginHelper;
    use FacebookFacebookSession;
    use FacebookFacebookSDKException;
    use FacebookHttpClientsFacebookHttpable;
    use FacebookHttpClientsFacebookCurl;
    use FacebookHttpClientsFacebookCurlHttpClient;

    use FacebookEntitiesAccessToken;
    use FacebookEntitiesSignedRequest;

    $iti=new FacebookSDKException;
    FacebookSession::setDefaultApplication('xxx','yyy');
    $page_id="655095094605502";
    $helper = new FacebookRedirectLoginHelper('http://ec2-54-64-18-188.ap-northeast-1.compute.amazonaws.com/faceb/callback.php&#039;);

    echo 'getLoginUrl() . ‘”>Login with facebook‘;

    callback.php

    getSessionFromRedirect();
    echo $session;
    } catch(FacebookRequestException $ex) {
    // When Facebook returns an error
    echo $ex->getMessage();
    echo “ai”;
    } catch(Exception $ex) {
    // When validation fails or other local issues
    echo $ex->getMessage();
    echo “hi”;
    }

    if(isset($session)){
    $request= new FacebookRequest($session,’GET’,’/me’);
    $response = $request->execute();
    $graphObject = $response->getGraphObject();
    var_dump($graphObject);
    } else{
    echo ‘getLoginUrl() . ‘”>Login with facebook‘;
    }

    $access_token=( new FacebookRequest($session,’GET’, ‘/’ . $page_id, array( ‘fields’ => ‘access_token’ ) ))->execute()->getGraphObject()->asArray();

    // save access token in variable for later use
    $access_token = $access_token[‘access_token’];

    $page_post=(new FacebookRequest($session,’POST’,’/’. $page_id .’/feed’, array(
    ‘access_token’ => $access_token,
    ‘name’ => ‘Facebook API: Posting As A Page using Graph API v2.x and PHP SDK 4.0.x’,
    ‘link’ => ‘http://ec2-54-64-18-188.ap-northeast-1.compute.amazonaws.com/faceb/call.php’,
    ‘picture’ => ‘http://ec2-54-64-18-188.ap-northeast-1.compute.amazonaws.com/tokub/image1.jpg’,
    ‘caption’ => ‘The Facebook API lets you post to Pages you administrate via the API. This tutorial shows you how to achieve this using the Facebook PHP SDK v4.0.x and Graph API 2.x.’,
    ‘message’ => ‘Check out my new blog post!’,
    ) ))->execute()->getGraphObject()->asArray();

    // return post_id
    print_r( $page_post );

    ?>

    I ‘m sorry to flood your blog with much source code,and paste confidentials.But I absolutely must finish my work until tomorrow morning.Can you say anything about my codes?

    Reply
    • Niraj Shah says:
      November 13, 2014 at 9:46 AM

      First off, remove the line $iti=new FacebookSDKException;. It’s not required. Second, add try…catch statements around the Facebook API calls so you can see where the error is coming from.

      Reply
    • devsk (@devsk75) says:
      December 17, 2014 at 2:36 AM

      hi tatsuyo – did u manage to get this sorted. i see that u r working on aws. i am having heaps of hurdles getting this to work .. could you help.

      Reply
  35. Amit Patel says:
    November 22, 2014 at 6:23 AM

    Hi Niraj
    But i can not get user’s country i mean location or friendlist i just get friends total count.

    Reply
    • Niraj Shah says:
      November 24, 2014 at 11:21 AM

      I cannot help you without source code or the query you’re using. Post a question on Stackoverflow and send me the link.

      Reply
  36. rasyid says:
    November 25, 2014 at 8:48 AM

    Why I can’t go to the next process (line 84 process) after login ? I always back to the login link

    Reply
    • Niraj Shah says:
      November 25, 2014 at 9:38 AM

      Are you getting any errors or exceptions with logging in?

      Reply
  37. rasyid says:
    November 25, 2014 at 10:23 AM

    No, I’m not getting any errors…

    Reply
    • rasyid says:
      November 25, 2014 at 9:27 PM

      But when I open it from the Firefox browser, I’m getting error message: couldn’t connect to host

      Reply
      • Niraj Shah says:
        November 27, 2014 at 11:30 AM

        Then it means your ISP is blocking connections to Facebook, which could be the reason for the error.

  38. Aniket Bhange says:
    November 28, 2014 at 4:37 AM

    I am facing an issue in asking permission to enduser for my facebook app as written in code i had ask manage page permission (manage_page) in scope parameter but I am getting blank data. can some body help me..
    this is the code i am using

    $loginUrl = $facebook->getLoginUrl(array(
    ‘scope’=>’publish_actions,manage_pages’
    ));

    Reply
    • Niraj Shah says:
      November 28, 2014 at 1:30 PM

      The issue is the your $loginUrl. Change your code to:

      $loginUrl = $facebook->getLoginUrl( array ( 'publish_actions', 'manage_pages' ) );

      i.e. You don’t need scope in the array. And the permissions are an array. It’s different to what you would have used in the old PHP SDK.

      Reply
  39. Robbie says:
    December 1, 2014 at 4:30 PM

    Hi there, great example! I have a couple of questions though. I’m able to get your example working fine. I see my profile data. I’m incorporating this into a wordpress plugin that I am trying to write. There are some changes that I want.

    For example, I want to have my plugin automatically login (i don’t want there to be the need to click Login. Perhaps maybe clicking it once would be ok, but then beyond that I’d like the neccessary info to be stored into wordpress).

    Next I want to grab the current users feed in json format. I’ll parse this feed and import it into a database.

    I want to display the feed on my website along with a feed of my twitter and instagram posts which were quite easy to deal with the api of those systems.

    So a couple of questions, do i need the authentication part if i only want a public user feed?

    Is there a way to automate the login in facebook approved way?

    How can i get my user feed?

    I had tried this, but it comes back blank.

    // graph api request for user data
    $request = new FacebookRequest(
    $session,
    ‘GET’,
    ‘/me/feed’
    );
    $response = $request->execute();
    // get response
    $graphObject = $response->getGraphObject()->asArray();

    Reply
    • Niraj Shah says:
      December 1, 2014 at 4:51 PM

      In order to get the user’s feed, you need to ask for the “read_stream” permission. Facebook also need to approve the user of this permission before it will work for users. You can get public feed information without asking for permission. As for login, you should always ask the user to Login – otherwise it could be classed as “forcing” the user, which Facebook doesn’t like.

      Reply
  40. Amitpal Singh says:
    December 5, 2014 at 6:43 PM

    How to get the person first name last name in your given app code. I have to fetch the erson name and image as well.

    Reply
    • Niraj Shah says:
      December 9, 2014 at 12:38 PM

      Have a look at the $graphObject variable on line 95. All you need to do is:

      echo $graphObject['first_name'] . ' ' . $graphObject['last_name'];
      

      Reply
  41. Mayank says:
    December 10, 2014 at 11:43 AM

    Hi Niraj,

    Great post. It gave me a very good start.
    I am fetching the uploaded photos of a user using
    $request = new FacebookRequest( $session, ‘GET’, ‘/me/photos/uploaded?limit=9’ );
    and setting the limit to 9, can you please tell me how I can implement the next and previous buttons that it just refreshes the results only.

    Thanks in advance.. 🙂

    Mayank

    Reply
    • Niraj Shah says:
      December 17, 2014 at 11:33 AM

      At the bottom of the response, you’ll see the ‘paging’ object. You can use the ‘next’ and ‘previous’ URLs to handle the pagination by making a new API call to each.

      Reply
      • Mayank says:
        December 17, 2014 at 11:55 AM

        Can you please guide how I can make the API calls to the next and previous URLs.

      • Niraj Shah says:
        December 17, 2014 at 11:59 AM

        Have a look at the response and you’ll see it. All you need to do is call the URL it gives you. Not that difficult to do yourself.

  42. devsk (@devsk75) says:
    December 17, 2014 at 3:52 AM

    chaining – u may want to correct – lines 91-96 not 41-44

    Reply
    • Niraj Shah says:
      December 17, 2014 at 11:36 AM

      Thanks for pointing that out. The lines had changed after each update!

      Reply
  43. devsk (@devsk75) says:
    December 17, 2014 at 8:18 AM

    Hi Niraj – very good article from the ones I have searched on the same topic. As I am a novice at all this I am facing some issues, from what I read along these comments some of these issues seem familiar (blank page).

    One of them is that SSL is required and you have said – “I use MAMP on Mac, with a self-signed certificate to develop locally.” Does that mean I need to enable SSL on my web server – i found this article at https://beeznest.wordpress.com/2008/04/25/how-to-configure-https-on-apache-2/ .. is this what I have to do.

    Acc to this link, looks like I need a domain name (am i right) – is there a way I can proceed without a domain name – would you be able to suggest any directions or links. Thanks!

    Reply
    • Niraj Shah says:
      December 17, 2014 at 11:40 AM

      On my localhost, I setup the domain http://sites.local using MAMP. MAMP Pro has a setting that lets you setup SSL on any domain, so I set it up to use that domain – there’s even an option to create a self-signed certification to use.

      The tutorial should be helpful – all you need to use is setup any domain you want and make sure the /etc/hosts file is setup correctly so it points to localhost.

      Reply
      • devsk (@devsk75) says:
        December 17, 2014 at 7:16 PM

        I am using Amazon AWS Linux. So, trying to figure if what the above link explains (ie. setup SSL on Apache) is what I should be doing.

      • Niraj Shah says:
        December 23, 2014 at 12:06 PM

        AWS will be using either httdp or Apache 2 as the web server. The steps should work for either one, although the locations of the config files will be different with each version.

  44. Jojoniko Netio says:
    December 25, 2014 at 6:00 AM

    Great Article.Save my time to update facebook sdk upgrade.

    Reply
  45. sbang4 says:
    December 26, 2014 at 12:53 AM

    you don’t need bunch of require_once(..) statements if you start a session before you use “use” statements

    Reply
    • Niraj Shah says:
      December 30, 2014 at 12:15 PM

      This is true if you use Composer as the classes are auto-loaded, but not if you want to use the SDK as stand-alone. If you don’t include the require_once statements, you’ll get a bunch of “Class ‘Facebook\FacebookSession’ not found” errors. Those errors will occur regardless of where you start the session.

      Reply
      • sbang4 says:
        December 30, 2014 at 12:35 PM

        I believe I used the SDK as it is.
        I’m not so sure about “Composer” but since I’ve never installed anything like it and removed composer.json file from the source I doubt that “Composer” is a matter.
        It still works like a charm with out it. Or am I accidentally using “Composer”??
        Let me know if i’m wrong.

      • Niraj Shah says:
        December 30, 2014 at 12:47 PM

        I’m not sure. Email me your sample code and if it works, I’ll updated my tutorial and credit you for the findings.

      • sbang4 says:
        December 30, 2014 at 12:56 PM

        This is the only difference I see right after session_start();

        // Skip these two lines if you’re using Composer
        define(‘FACEBOOK_SDK_V4_SRC_DIR’, __DIR__ . ‘/sdk/src/Facebook/’);
        require __DIR__ . ‘/sdk/autoload.php’;

        I guess these two lines won’t be needed if you use composer as the comment says..

      • sbang4 says:
        December 30, 2014 at 12:58 PM

        I looked into that autoload.php file
        yea it requires bunch of files needed eventually. so basically it’s doing the same thing.

      • Niraj Shah says:
        December 30, 2014 at 1:08 PM

        Yes, the autoload.php file makes it easier to include the files from the SDK. That would explain why you don’t need the require_once statements.

  46. urvashi says:
    January 23, 2015 at 7:28 AM

    hi,

    i want to add multiple Facebook accounts at a same time.(like Google can add multiple account and also we can access that accounts separately.)i also want to add Facebook page and group.for that i want when i will click on connect page then it will connect only page and also give option for choosing profile and group .using php .Please reply .

    Reply
    • Niraj Shah says:
      January 23, 2015 at 9:21 AM

      Nothing something you can do with the API and SDK unfortunately. The multiple login with Google is built into Google itself, and accounts for the fact that a user can have multiple gmail accounts (e.g. a personal one and Google Apps / Business one). With Facebook, it’s assumed that a user will only have one account (personal) so there is no built-in option to handle multiple login scenarios.

      Reply
  47. Urvashi Tiwari says:
    February 3, 2015 at 9:20 AM

    thanks niraj

    Reply
  48. mwsasser says:
    February 5, 2015 at 2:02 PM

    I want to thank you for keeping up to date on this. 🙂

    Reply
  49. Facebook API: Using the Facebook PHP SDK v4.1.x | Web Niraj says:
    February 19, 2015 at 6:22 PM

    […] how the new version works. This is the first major update to the SDK since it was released in May 2014, and one that has been mostly lead by the open-source […]

    Reply
  50. Predrag Rodić says:
    February 21, 2015 at 10:57 AM

    Hello Niraj, can i get your opinion on this question http://stackoverflow.com/questions/28626393/best-way-to-tracking-user-status-under-tab

    Reply
    • Niraj Shah says:
      February 21, 2015 at 10:38 PM

      Are you taking about authenticating the user across multiple pages (not sure if this is what you mean by status)? If so, the best way to achieve this is using PHP $_SESSION or cookies. Cookies would be your best bet here – the only thing you need in the cookie is the user’s access_token, which can be used to authenticate the user across the various pages.

      Reply
      • Predrag Rodić says:
        February 23, 2015 at 8:28 AM

        Dear Niraj,
        apologies for the late answer. I just wanted to say thanks, have been following you for a quite some time and your opinion means a lot to me. I’ve thought that those sessions were right solution, but when expert says that it should be done with cookies, than I’ll do it in that way and follow performances of the app.

        Once more, thank you Niraj very much!

Comment navigation

← Older Comments
Newer Comments →

Leave a Reply to tudorCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

StackExchange / StackOverflow

profile for Niraj Shah on Stack Exchange, a network of free, community-driven Q&A sites

Support Me

Buy Me a Coffee

PSN Profile

Tags

ACL Amazon Amazon Web Services Android Android 4.4 KitKat Android 5.0 Lollipop Apache Backup Bug Command Line Cordova cPanel / WHM Facebook Facebook Graph API Facebook PHP SDK 4.0 Facebook Social Plugins Fan Page Firewall Flash Gadget Geolocation Google Nexus 5 Hacking HTML5 iOS JavaScript jQuery Laravel 5 Linux NodeJS Parse PDF PHP Plugin Portfolio PS4 Review Security Server SSH SSL Sysadmin Tutorial WordPress WordPress Plugins
© 2011-2025 Niraj Shah
  • Blog
  • Portfolio
  • WordPress
  • About Me
  • Contact Me
  • Privacy Policy
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Privacy Policy