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!

This post was originally published on May 30, 2014 and last updated March 9, 2018.

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();
  exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$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

Author: Ben Marshall

Red Bull Addict, Self-Proclaimed Grill Master, Entrepreneur, Workaholic, Front End Engineer, SEO/SM Strategist, Web Developer, Blogger

52 thoughts on “Facebook PHP SDK — a simple guide!”

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

        Thanks.

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

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

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

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

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

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

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

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

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

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

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

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

    Thanks,
    Matt

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

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

  13. 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();
    }

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

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

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

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

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

Leave a Reply

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