Facebook PHP SDK — a simple guide!

53 Comments

Join the Conversation

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

Comments

  1. Nirksa
    at 11:16 pm

    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

    • at 8:06 am

      Sounds like you’ve got some malformed code. Take a look at the example and compare to what you’ve got.

  2. Tuareg
    at 6:46 am

    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?

    • at 2:34 pm

      I’ve updated the post to provide more details that should answer your question. Let me know if you run into any problems.

  3. Dimitris Sarmis
    at 8:30 am

    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.

    • at 2:34 pm

      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.

  4. boshigt
    at 8:45 pm

    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.

      • dany
        at 10:09 am

        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?

  5. Matt
    at 2:26 pm

    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

  6. at 8:14 pm

    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?

    • at 7:57 am

      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.

Leave a Reply

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

All comments are held for moderation. I'll publish all comments that are 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.

%d bloggers like this: