Facebook PHP SDK — a simple guide!

Bring the power of Facebook to your application using the Facebook PHP SDK — a powerful library allowing you to retrieve user information, publish to profiles, enable Facebook registrations, logins and more!

The Facebook PHP SDK is a powerful library that allows developers to easily integrate Facebook login and make requests to the Graph API. In this post, we’ll go over how to install, initialize and perform operations like posting to timelines, user registrations, logins and more!

Facebook Application Prerequisite

Before we dive in, you’ll need to create an app on Facebook to use the Facebook PHP SDK. You’ll receive an App ID and App Secret that will be needed when initializing the Facebook PHP SDK library. For more information on creating an app, see Facebook’s Register and Configure an App tutorial.

Important: Be sure to update the App Domains setting under Settings > Basic in the App Dashboard.

Pro Tip: In development and/or on your local? Create a test app. Test apps have their own App ID, App Secret and settings. This allows you update App Domains specific to the environment.

Facebook PHP SDK Installation

The Facebook PHP SDK can be installed with Composer:

composer require facebook/graph-sdk

Are you upgrading from v4.x? Facebook PHP SDK v5.x introduced breaking changes. Please read the upgrade guide before upgrading.

Note: This version of the Facebook SDK for PHP requires PHP 5.4 or greater.

Facebook PHP SDK Usage

Here’s a simple GET example of how a user’s profile and outputting the user’s name:

require_once __DIR__ . '/vendor/autoload.php'; // change path as needed

$fb = new \Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.10',
  //'default_access_token' => '{access-token}', // optional

// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
//   $helper = $fb->getRedirectLoginHelper();
//   $helper = $fb->getJavaScriptHelper();
//   $helper = $fb->getCanvasHelper();
//   $helper = $fb->getPageTabHelper();

try {
  // Get the \Facebook\GraphNodes\GraphUser object for the current user.
  // If you provided a 'default_access_token', the '{access-token}' is optional.
  $response = $fb->get('/me', '{access-token}');
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();

$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();

That’s the quick and dirty that just about every other post out there on the topic of using the Facebook PHP SDK goes.

Integrate the Facebook PHP SDK

Unless you’re an experienced programmer, the example below probably doesn’t get you to where you want to be. Keep reading for a step-by-step guide on how to integrate the Facebook PHP SDK into your application.

Continue Reading: Facebook PHP SDK App Integration

1 2


  1. VinoGautham February 10, 2020

    Hi Ben, i am upgrading Facebook PHP SDK from Version 3.2.1 to Version 5.7.0 to one of my FB canvas app, First what i did was, i analysed how the existing implementation on V 3.2.1, so i have replaced all those methods with the equivalent method on V5.7.0, after all the implementation, my game is loading fine after few minutes it started reloading on its own.. it kept reloading. looks like authentication issue.. i found out that i am getting user_id sometime, but sometime the user_id is returning null, what could be the problem.. i am new to PHP. do i need to store the user_id in $SESSION[] ?. whether PHP SDK 5.7.0 handles native PHP SESSION on its own? i am looking forward to hear from you.

  2. Hi Ben,

    This is such a great article and helped me a lot.

    Please revise this section “Step 3: Making Requests” as Facebook doesn’t allow posting to the user’s feed any more.


  3. Thanks for sharing this. I’ve been trying to learn a little PHP. Great post for me and people who already use other languages like asp or asp.net and want to explore PHP. This is very helpful. Keep on the great work. I just want to say that there is no need to dive too deep in PHP if you don’t want to. A versatile coder can just pick what they need for a particular scenario.

  4. got this error “Undefined variable: config fb-callback.php”
    after doing search and found this
    The variable $config[‘app_id’] is undefined, use the app id directly:


    now the error doesnt appear.
    Hope it might usefull to anyone

  5. Nabin Bhandari September 3, 2018

    how to get users facebook page and me/accounts/feeds

  6. Tom Dings April 9, 2018

    May I let you all know Facebook is asking since a little while to redirect the callback to a secured – https – enabled website. Maybe you all were aware of it already. I just found out and wanted to share it with you.

    Happy programming and share your results. I am curious what people were capable of building.

    Thank you and enjoy your day!

  7. Rameez Raja February 22, 2018

    Video is uploading to my own facebook timeline successfully, but if upload from another account it show error of permission.

    I want every user upload to their own timeline.

    Thank you

  8. HI. This is a great article, one of the best explanations i have found in the web about this subject.
    I have a question for you, maybe you now how to solve it.
    Is there any way to get an access token, stright from the php code, having my login information (facebook user, password), so I don’t need to use any login screen? My point is to try to get a token from my php code using the login data as a parameter inside the code. I guess some kind of oauth against facebook server through php..

  9. Good article!
    Great help to me, Thank you.

  10. Nice tutorial.how can i also get a facebook user history??please any help

  11. This works great if i want to use the Facebook api on my home computer. I dont understand I guess Im not very smart, Why would you want to use it locally on your own server, How does this composer install help me actually get this on my web site working on the internet? please help me.

  12. themood June 8, 2017

    I would like to thank and commend you on this lesson. It really helped me i have been struggling for months with this Facebook graph. you explained it so clear. Facebook really needs to hire you. I could follow your instructions just fine and my demos all worked first time on version 5. When i follow the Facebook examples in Facebook developer I got lost every time. So THANK YOU!!!!!!

  13. Hi Ben,
    Thank you for your very detailed article. It helped me quickly rewrite my old API using code. =)

  14. Great article!

    BTW, what happened to the getSession() method from v4 ?

    I have this code and now is useless.

    $helper = new FacebookPageTabHelper();
    $helper = $fb->getPageTabHelper();
    if ($helper->getPageId()) {
    $data[‘page’] = [
    ‘id’ => $helper->getPageId(),
    ‘admin’ => $helper->isAdmin(),
    // ‘liked’ => $helper->isLiked(),
    ‘liked’ => false
    if ($helper->getSession()) {
    $session = $helper->getSession();

  15. I am getting this error.
    Does this require me to get permissions from facebook for each action mentioned in the Status and Review section of my app.
    Fatal error: Uncaught exception ‘FacebookFacebookPermissionException’ with message ‘(#200) The user hasn’t authorized the application to perform this action’

    • Looks like the access token may be incorrect or your session data isn’t getting passed over. Can I see the code you’re using?

  16. Awesome content.

  17. I’ve followed your steps, looked at the demo files, etc… but I keep running into a problem where my session isn’t ever set, so all I get is the Login URL every time. Could this have something to do with the new changes Facebook is making …?

    I feel like I had this exact problem before the last time I set up FB integration last year, and no one has examples that work like they’re supposed to. Just to be clear, the redirect_uri should take me back this same file location, right?

    • I’ve updated the tutorial with the new v5 (4.1) features. Also provided some more example that should help you out. Let me know if you still run into problems.

  18. I used this article to get me going and everything is working like I’d expect. Was wondering if anyone here knows how to get it to work with WordPress?

    Everything works like I want except I lose the session when I navigate the site after I login.

    I tried to use the “init” action hook but get this error from the SDK “Session not active, could not load state.”

    Any help/direction would be sweet! and… thanks for the article.


  19. for developing facebook can i using localhost for testing?

      • oke thank you, but when i upload to hosting and i try access i get error liki this
        “Fatal error: Cannot access protected property FacebookFacebookSDKException::$message in /home/u648397598/public_html/facebook/index.php on line 62”
        can you fix this problem?

  20. This is GREAT post man ^^. Saved my day. However is there any way to get cleaner url after login. Mine is little messy with “code” and “state” parameter.

  21. Dimitris Sarmis November 25, 2014

    Hello, i am a bit confused about some things if you could explain me i would appreciated a lot.
    I am trying to create a facebook app with both platforms of Facebook Canvas and Page tab.
    I am currently working at Page tab. I want to use the php sdk to create the Auth dialog.
    Lets say my file for the facebook session and stuff is hosted at demo.myhost.gr/app1/fbmain.php
    So my App Domains is demo.myhost.gr
    If i have understood correctly i am supposed to use the FacebookRedirectLoginHelper($redirect_uri)
    and $redirect_uri must be https://demo.myhost.gr/app1/fbmain.php
    This means that when the user will click at $loginUrl he will see the auth dialog and then he will leave Facebook and go at $redirect_uri.
    So i must save the session and have a redirection back to my Facebook Page and app.
    Am i correct till here?
    Also the Log out’ it gives me a white page inside the Faceboook Tab, with no auth dialog.

    • Yes, that’s basically it. I’ve updated the post with more details on the whole process which should help. Let me know if you still run into troubles.

  22. thanks buddy, this work for me.
    but, how to get token like on https://developers.facebook.com/docs/facebook-login/access-tokens/ ???

    i try but have many error.
    actually about, Long-Lived Tokens.


  23. I’m new at developing Facebook. I’m trying to use your example on my server but it back with “Parse error” for use FacebookFacebookRequest; why?

  24. Hi,

    I copied your code from demo, and created fb applicaiton and security token and app id were taken, But i’ m getting this error
    Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in C:wampwwwfacebookindex.php on line 23

  25. Really awesome content, it helped me allot, thanks!

  26. I tried your code, but every time I refresh the canvas page it asks me to login again. If older version of SDK, the user needed to add the app just once. Do you have any fix for that?

  27. Thinh Nguyen August 18, 2014

    Thanks for the code, it works perfectly!

    But I’m stuck with this: I try to change the request url, it returns data nicely in the Facebook Graph API Explorer Tool, but in my site on localhost (appId and appSecret are correct) just returns a null array! Do you have any idea?

    • Make sure you set the app’s App Domains setting to the domain you’ll be using the app on (e.g. localhost.dev). Otherwise, you won’t have access to the API.

      it’s a good idea to create a Test App. This is especially useful when working on a local environment. Test Apps have their own App ID, App Secret and settings. This allows you to set the App Domains setting to your local environment URL without affecting the production version of your app.

  28. Can you please explain , where do we have to put (starting with “session_start()” ) those coding in our hosting file. do we have to add with our index.php?

  29. i follow ur code but it didn’t generates the access token can u tell me where did i made mistake

  30. This tutorial has really helped me a lot as I get started with the Facebook SDK for PHP. Many thanks for posting it!

    I was wondering what is the purpose of the code on line 76? At this point in your code it seems that you have already verified a session. It doesn’t seem necessary to call FacebookSession() again – or am I missing something?

    Thanks again for a great tutorial 🙂

  31. Rahulg FDEV August 3, 2014

    can you tell me how to configure in yii framework

  32. “PHP message: PHP Fatal error: Cannot use Facebook\FacebookCurl as FacebookCurl because the name is already in use

  33. Thanks,your code is working fine.

  34. there is problem with session, after 2 hours it gets destroyed , and i dont know how to renew it, it will then will throw error about authorization shit all the time, refresh wont help, only deleting cookies helped

    btw i tried the example with codeigniter, not without

  35. Niko Jojo July 22, 2014

    Using version 4.0.9. Above example don’t works to me.

    • Can you be more specific? Just tested the code with the latest and provided downloadable demo files for an example. Try those out and see if it works for you.

      • Hi, there your code where you get token:
        I tried the same way, but there are token=’app_id|secret_id’, so this is not that secret token that generate facebook to create FacebookSession and use their API, and i get exception:
        An active access token must be used to query information about the current user.
        I wanna store access token, but can’t understand how to get it.

      • Ben, hey great job on your tut. I have a general question about Facebook and their Marketing API which is kinda off topic of what you did above. Would you be helpful and just spot me in the right direction on how can I use a date picker to use for $params (time_range ‘since’ and ‘until’) I mean I have everything else completed the only thing I can’t figure out is how to store this using ajax with the code I have. Just wondering if you ever accomplished this and if so maybe a little pointer would be awesome.


Leave a Reply

Your email address will not be published. Required fields are marked *

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

All comments are held for moderation and only published when on topic and not rude. You'll even get little stars if you do an extra good job.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.

icon-search icon-link