Facebook PHP SDK v5.x (4.1) — a complete guide!

Facebook SDK PHP is a powerful library allowing you to retrieve user information, publish to profiles, enable Facebook registrations, logins and more. Learn how to easily implement the Facebook SDK PHP library (v4) with easy to follow examples to get your site integrated quickly.

Implement the Facebook SDK 5.x (4.1) for PHP to enable one-click registrations & logins, gain access to user photos, timelines and even publish to profiles.

Update (April 29, 2015): Facebook PHP SDK 5.x? What happened to 4.1 you ask? The Facebook PHP SDK will start following SemVer starting with v5.0. Before the decision to adopt SemVer, the official Facebook PHP SDK was going to be released as v4.1. But now v4.1 is just an alias to v5.0.0. So any references to 4.1 can be safely aliased to v5.0.0. For more information, see F8 2015 Facebook Developer Conference and the new PHP SDK.


Facebook PHP SDK Complete Guide

Installing the Facebook PHP SDK

Using the Facebook PHP SDK

Facebook PHP SDK Examples

Download Demo Files (Facebook PHP SDK v4)


Facebook PHP SDK Requirements

Version 5 of the SDK runs on PHP 5.4 or greater with the mbstring extension installed.

Facebook Application Prerequisite

You’ll need to create an app in Facebook in order to use the Facebook PHP SDK. Once created, you’ll be provided with an App ID and App Secret. For more information on creating an app, see Facebook’s Creating App Details tutorial.

IMPORTANT: Don’t forget to set the App Domains when creating an app to where your code is hosted.
PRO TIP: During development, 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 App Domains to your local environment without affecting production.

Installing the PHP Facebook SDK

Composer Installation

I recommended installing the Facebook PHP SDK with Composer. Start by creating a file named composer.json and place it in the docroot of your web app. Add the following lines to it:

{
  "require" : {
    "facebook/php-sdk-v4": "~5.0@dev"
  }
}
Versioning Note: As of writing, v5 is still in development so you need to use the @dev minimum-stability flag. In addition, the Facebook PHP SDK v4 did not follow Semantic Versioning (SemVer). The version schema for the SDK in v4 was 4.MAJOR.MINOR|PATCH. That’s why you would have to use 3 version numbers with the ~ operator like ~4.0.0. But starting with v5, the SDK follows SemVer so we just use 2 version numbers: ~5.0.

In Terminal from the project’s docroot (same directory we placed the composer.json file), run:

composer update

This will download the Facebook PHP SDK v5.

$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing facebook/php-sdk-v4 (dev-master cde1d8b)
    Cloning cde1d8b9f32fc375a8748838eaac1b6d4f48fa5e

facebook/php-sdk-v4 suggests installing guzzlehttp/guzzle (Allows for implementation of the Guzzle HTTP client)
Writing lock file
Generating autoload files
Facebook PHP SDK v4: Composer Installation

If you prefer to use v4 of the Facebook PHP SDK, use ~4.0.*:

{
  "require" : {
    "facebook/php-sdk-v4": "~4.0.*"
  }
}

Manual Installation

You don’t use Composer? You should! But if you’re needing a quick-and-dirty install, download the zip from GitHub and extract the files on your computer somewhere.

Move the folder located at src/Facebook to the location in your web app where you store 3rd-party vendor files. You can also rename the folder to facebook-php-sdk-v5 or something.


Initializing the PHP Facebook SDK

Now that we have the dependencies downloaded, we’re going to initialize the Facebook PHP SDK. Create a file in your web app docroot and name it app.php. If you used Composer to install the Facebook PHP SDK, include the Composer autoloader:

<?php
// Pass session data over.
session_start();

// Include the required dependencies.
require_once( 'vendor/autoload.php' );

If you manually installed the SDK and assuming you moved and renamed the src/Facebook folder to /my/app/third_party/facebook-php-sdk-v5, in your web framework’s bootstrap scripts or at the top of your PHP script, you need to include the autoloader.

// Pass session data over.
session_start();

// Include the required dependencies.
require( __DIR__.'/third_party/facebook-php-sdk-v5/autoload.php' );
Important: Don’t forget to pass the server session data over if you haven’t already. This keeps the user’s information stored so the permissions persist as the user navigates your app.

To initialize the SDK, we need to pass the app_id, app_secret and default_graph_version.

// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '{app-id}',
  'app_secret'            => '{app-secret}',
  'default_graph_version' => 'v2.3',
]);

You’ll notice that v5 is namespaced under the Facebook\ namespace.

At first glance you might think v5 also has one big base class that does all the things. In reality, v5 consists of many, many different classes and the Facebook\Facebook just ties them all together.

Be sure to change the {app-id} and {app-secret} to your Facebook credentials provided when you created the app.

Facebook PHP SDK v4: Initializing the PHP Facebook SDK

If you’re using v4 of the Facebook PHP SDK, you can initialize the SDK with the following.

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

// Initialize the Facebook SDK.
FacebookSession::setDefaultApplication( '{app-id}', '{app-secret}' );


Authentication & Authorization

Checking If A User Is Logged In

If a signed request can be detected, decoded, validated and it contains a user_id in the payload, then the user has previously authenticated the app and can be considered “logged in”. You do this with “helpers”.

# Facebook PHP SDK v5: Check Login Status Example

// Choose your app context helper
$helper = $fb->getCanvasHelper();
//$helper = $fb->getPageTabHelper();
//$helper = $fb->getJavaScriptHelper();

// Grab the signed request entity
$sr = $helper->getSignedRequest();

// Get the user ID if signed request exists
$user = $sr ? $sr->getUserId() : null;

if ( $user ) {
  try {

    // Get the access token
    $accessToken = $helper->getAccessToken();
  } catch( Facebook\Exceptions\FacebookSDKException $e ) {

    // There was an error communicating with Graph
    echo $e->getMessage();
    exit;
  }
}

Getting Access Tokens

Access Tokens from Facebook Login (manual redirect)

You can implement Facebook Login (OAuth 2.0) with the PHP SDK by using the FacebookRedirectLoginHelper. An instance of this helper can be obtained from the Facebook super service by using the getRedirectLoginHelper() method.

$fb = new Facebook\Facebook([/* . . . */]);

$helper = $fb->getRedirectLoginHelper();
Facebook PHP SDK v4: Create instance of FacebookRedirectLoginHelper

$helper = new FacebookRedirectLoginHelper('http://example.com/app.php');

Once you get an instance of the FacebookRedirectLoginHelper, you can use it to generate an authorization URL to start an OAuth 2.0 flow. You pass to this method, the redirect URL (where the user is redirected to after approving or denying the app authorization request) and an array of permissions you want to ask them for.

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email', 'user_posts']; // optional
$callback    = 'http://example.com/app.php';
$loginUrl    = $helper->getLoginUrl($callback, $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';

Now you can grab an instance of the FacebookRedirectLoginHelper again and call the getAccessToken() method once the user has clicked on the login link.

$accessToken = $helper->getAccessToken();

This one-liner is fine if all goes well, but there are a number of possible scenarios our callback script should account for.

  1. If all goes well, $accessToken will be an instance of the AccessToken entity. (See “The AccessToken Entity” section below.)
  2. If there was a problem communicating with the Graph API, the getAccessToken() method will throw a FacebookSDKException, so you’ll want to wrap that bad boy with a try/catch to catch the exception and display a proper error message to the user.
  3. If the user denied the request, $accessToken will be null. What this really means is that the SDK could not find an OAuth code in the GET params. Keep reading.
  4. If there is no code param, there should be a number of error_* params that describe why there’s no code. The error params can be accessed using the following methods: getError(), getErrorCode(), getErrorReason(), and getErrorDescription(). We can assume that if getError() returns null, then all the other error getter methods will also return null.
  5. In the event that both getAccessToken() and getError() methods return null, then whoever is hitting your callback endpoint ain’t coming from Facebook. In this situation I generally return a 400 Bad Request HTTP response. It’s also probably a good idea to log this suspicious request.

If we update our callback script to account for all these scenarios, we get a lot more bullet-proof code.

$fb = new Facebook\Facebook([/* . . . */]);

$helper = $fb->getRedirectLoginHelper();
try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  echo $e->getMessage();
  exit;
}

if (isset($accessToken)) {
  // User authenticated your app!
  // Save the access token to a session and redirect
  $_SESSION['facebook_access_token'] = (string) $accessToken;
  // Log them into your web framework here . . .
  echo 'Successfully logged in!';
  exit;
} elseif ($helper->getError()) {
  // The user denied the request
  // You could log this data . . .
  var_dump($helper->getError());
  var_dump($helper->getErrorCode());
  var_dump($helper->getErrorReason());
  var_dump($helper->getErrorDescription());
  // You could display a message to the user
  // being all like, "What? You don't like me?"
  exit;
}

// If they've gotten this far, they shouldn't be here
http_response_code(400);
exit;

This will output a link users can click on to login through Facebook. When clicked, the use will be redirect to Facebook to log in if not already. Once logged it, users will be directed back to our redirect URL with an appended code parameter that we’ll use to retrieve and store the access token. If all worked, you should see Successfully logged in!

Facebook PHP SDK v4: Access Tokens from Facebook Login (manual redirect)

If using the Facebook PHP SDK v4, you can get access tokens with the following:

try {
    if ( isset( $_SESSION['access_token'] ) ) {
        // Check if an access token has already been set.
        $session = new FacebookSession( $_SESSION['access_token'] );
    } else {
        // Get access token from the code parameter in the URL.
        $session = $helper->getSessionFromRedirect();
    }
} catch( FacebookRequestException $ex ) {

    // When Facebook returns an error.
    print_r( $ex );
} catch( \Exception $ex ) {

    // When validation fails or other local issues.
    print_r( $ex );
}
if ( isset( $session ) ) {

    // Retrieve & store the access token in a session.
    $_SESSION['access_token'] = $session->getToken();
    // Logged in
    echo 'Successfully logged in!';
} else {

    // Generate the login URL for Facebook authentication.
    $loginUrl = $helper->getLoginUrl();
    echo '<a href="' . $loginUrl . '">Login</a>';
}

Access Tokens from App Canvas/Page Tabs

When you have an app that runs in app canvas or a Page tab, an access token can be obtained from the signed request that is POSTed to your app but this will only ever be true if the user has already authorized your app. If the user has not authorized your app yet, you’ll need to log them in using the OAuth 2.0 login flow as described in the section above or by using the JavaScript SDK.

If an access token exists in the signed request, it can be obtained using the FacebookCanvasHelper. An instance of this helper can be generated from the Facebook super service by using the getCanvasHelper() method.

$fb = new Facebook\Facebook([/* . . . */]);

$helper = $fb->getCanvasHelper();
try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  // Or there was a problem validating the signed request
  echo $e->getMessage();
  exit;
}

if ($accessToken) {
  echo 'Successfully logged in!';
}

Page tabs and canvas apps are virtually identical but there are a few important differences. One added feature of a Page tab app is that the signed request will contain additional data about the parent page.

There is a FacebookPageTabHelper that helps you interface with the components available to your Page tab. The page tab helper extends from the FacebookCanvasHelper so all the methods are adopted as well. And there are a few additional methods you get when using the FacebookPageTabHelper.

$fb = new Facebook\Facebook([/* . . . */]);

$helper = $fb->getPageTabHelper();

// Returns info about the parent page
$pageData = $helper->getPageData();

// A boolean of whether or not the
// authenticated user is an admin
// of the parent page
$isAdmin = $helper->isAdmin();

// The ID of the parent page
$pageId = $helper->getPageId();

Access Tokens from the JavaScript SDK

The JavaScript SDK has a really great UI for Facebook Login. It is a better user experience to use the JavaScript SDK to authenticate a user into your app than it is to use the PHP SDK’s OAuth 2.0 flow with the FacebookRedirectLoginHelper.

I know what you’re thinking: Once I log a user in with the JavaScript SDK, how does my PHP script access the access token?

By default the JavaScript SDK won’t store any info about the user on your domain unless you explicitly tell it to. So in your FB.init() method, you’ll need to enable the cookie option with {cookie:true}. This tells the JavaScript SDK to set a cookie on your domain that contains a signed request with information about the authenticated user.

FB.init({
  appId   : '{app-id}',
  cookie  : true,
  version : 'v2.3'
});

If an access token exists in the signed request that was set by the JavaScript SDK, it can be obtained using the FacebookJavaScriptHelper. An instance of this helper can be generated from the Facebook super service by using the getJavaScriptHelper() method.

$fb = new Facebook\Facebook([/* . . . */]);

$helper = $fb->getJavaScriptHelper();
try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  // Or there was a problem validating the signed request
  echo $e->getMessage();
  exit;
}

if ($accessToken) {
  echo 'Successfully logged in!';
}

About Access Tokens

Access tokens are represented with an AccessToken entity. There are two ways to get the access token as a plain-old string.

// These statements are equivalent
echo (string) $accessToken;
echo $accessToken->getValue();

Having AccessToken entities gives us some more power when handling access tokens. For example, you can do a strict check to ensure that you definitely have an access token.

if ($accessToken instanceof Facebook\Authentication\AccessToken) {
  // Logged in.
}

You can also typehint function & method arguments that take an access token.

function (Facebook\Authentication\AccessToken $token) {
  // . . .
}

There are also a number of handy methods on the AccessToken entity.

// Returns expiration as a DateTime entity
$expiresAt = $accessToken->getExpiresAt();

// Returns boolean
$expired = $accessToken->isExpired();

// Returns boolean
$isLong = $accessToken->isLongLived();

// Returns boolean
$isAppToken = $accessToken->isAppAccessToken();

// Returns the app secret proof as a string
// This is used to sign requests to the Graph API
// All requests made using the PHP SDK are
// signed automatically for you
$proof = $accessToken->getAppSecretProof('{app-secret}');

Getting a Long-Lived (Extended) Access Token

You can exchange a short-lived access token for a long-lived access token by generating an instance of the OAuth2Client() by using the getOAuth2Client() method on the Facebook super service.

$cilent = $fb->getOAuth2Client();

try {
  // Returns a long-lived access token
  $accessToken = $cilent->getLongLivedAccessToken('{short-lived-token}');
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  echo $e->getMessage();
  exit;
}

The OAuth2Client has a number of cool features like a debugToken() method that returns an AccessTokenMetadata entity with information about the access token to be used to validate against or debug.

try {
  $metaData = $cilent->debugToken('{access-token}');
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  echo $e->getMessage();
  exit;
}

var_dump($metaData->getAppId());
var_dump($metaData->getApplication());
var_dump($metaData->isError());
var_dump($metaData->getIssuedAt());

// These all throw a FacebookSDKException
$metaData->validateAppId('{app-id}');
$metaData->validateUserId('{user-id}');
$metaData->validateExpiration();

Application Permissions

It’s important that you think about what permissions you’ll need for your site before your users start using it. If you ever need to update them, users will have to re-authorize the app. Once you have a list of permissions, pass them to the getLoginURL method as an array:

// Requested permissions - optional
$permissions = array(
    'email',
    'user_location',
    'user_birthday'
);

// Get login URL
$loginUrl = $helper->getLoginUrl($callback, $permissions);
Facebook PHP SDK v4: Application Permissions

// Requested permissions - optional
$permissions = array(
    'email',
    'user_location',
    'user_birthday'
);

// Get login URL
$loginUrl = $helper->getLoginUrl( $permissions );

If no permissions are provided, it’ll use Facebook’s default public_profile permission. Here’s a list of some common permissions:

User permission Description
public_profile Gives access to a subset of a person’s public profile:

  • id
  • name
  • first_name
  • last_name
  • link
  • gender
  • locale
  • age_range
email Provides access to the user’s primary email address in the email property on the user object.
user_location Provides access to the user’s current city as the location property.
user_birthday Provides access to the birthday.

See the full list of available permissions.


Making Requests to the Graph API

Once we’ve successfully logged in, we can begin making calls to the Graph API. The Graph API only supports the GET, POST and DELETE HTTP verbs. In v5, each of these verbs get their own corresponding method.

// GET request.
$res = $fb->get('/me', '{access-token}');

// POST request.
$res = $fb->post('/me/feed', $data, '{access-token}');

// DELETE request.
$res = $fb->delete('/123', $data, '{access-token}');

If you don’t want to have to send in '{access-token}' with every method call in v5, you can use the setDefaultAccessToken() method.

$fb->setDefaultAccessToken('{access-token}');

# These will fall back to the default access token
$res = $fb->get('/me');
$res = $fb->post('/me/feed', $data);
$res = $fb->delete('/123', $data);

The responses from the get(), post() & delete() methods return a FacebookResponse entity which is an object that represents an HTTP response from the Graph API.

If all you want is a plain-old PHP array, you call the getDecodedBody() method on the FacebookResponse entity.

// Response example.
$res = $fb->get('/me');

var_dump($res->getDecodedBody());

// array(10) { ...

v5 can return the response data as a collection which can be really handy for performing actions on the response data.

I won’t get into too much detail with this, but the collections come in the form of GraphObjects and they can be obtained from the FacebookResponse entity using the getGraphObject() method.

// Response example.
$res = $fb->get('/me');

$node = $res->getGraphObject();

var_dump($node->getProperty('id'));
// string(3) "123"

// Functional-style!
$node->map(function($value, $key) {
  // . . .
});

Handling Exceptions

Sometimes the Graph API will return an error response. Sad face. In v5 a FacebookSDKException will be thrown if something goes wrong.

try {
  $res = $fb->get('/123');
} catch (Facebook\Exceptions\FacebookSDKException $e) {
  echo $e->getMessage();
  exit;
}

There are more than just the base FacebookSDKException in v5 but I won’t get into too much detail on the other types of exceptions. But know that the other exceptions extend from FacebookSDKException so you can be assured that whenever you catch FacebookSDKException, you’re catching any of the extended exceptions as well.

The FacebookSDKException is not limited to error responses from the Graph API. There are other instances when a base FacebookSDKException might be thrown in v5. Some examples include a signed request fails to validate, a file you want to upload cannot be found and so on.

Facebook PHP SDK v4: Making Requests to the Graph API

try {
    $me = (new FacebookRequest(
        $session, 'GET', '/me'
    ))->execute()->getGraphObject(GraphUser::className());

    // Output user name.
    echo $me->getName();
} catch (FacebookRequestException $ex) {

    // The Graph API returned an error.
    print_r( $ex );
} catch (\Exception $ex) {

    // Some other error occurred.
    print_r( $ex );
}

If all went well, you should see your Facebook name. You can also chain these methods:

$me = ( new FacebookRequest(
    $session, 'GET', '/me'
) )->execute()->getGraphObject( GraphUser::className() );


Facebook PHP SDK Examples

Once you have a session, you’ll have access to the all-powerful API. You can use this API to retrieve user’s information, implement one-click registrations, logins, publish to profiles and more.
Check out the examples below to get the Facebook SDK PHP library (v5.x) integrated quickly.

One-Click Registration & Login

Here’s a basic example of how to use the Facebook PHP SDK v5 to enable one-click registrations and logins:

<?php
# Facebook PHP SDK v5: One-Click Registration & Login Example

// Pass session data to script (only if not already included in your app).
session_start();

// Include the required Composer dependencies.
require_once( 'vendor/autoload.php' );

// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '{app-id}',
  'app_secret'            => '{app-secret}',
  'default_graph_version' => 'v2.3',
]);

// Check if the user is logged in.
$helper = $fb->getRedirectLoginHelper();
try {
  $accessToken = $helper->getAccessToken();
} catch( Facebook\Exceptions\FacebookSDKException $e ) {

  // There was an error communicating with Graph
  echo $e->getMessage();
  exit;
}

if ( isset( $accessToken ) ) {

  // User authenticated your app!
  // Save the access token to a session and redirect
  $_SESSION['facebook_access_token'] = ( string ) $accessToken;

  // Register or log the user in...
  exit;
}
elseif ( $helper->getError() ) {

  // The user denied the request
  // You could log this data . . .
  var_dump( $helper->getError() );
  var_dump( $helper->getErrorCode() );
  var_dump( $helper->getErrorReason() );
  var_dump( $helper->getErrorDescription() );

  // You could display a message to the user
  // being all like, "What? You don't like me?"
  exit;
}

// If they've gotten this far, they shouldn't be here
http_response_code(400);
exit;
Facebook PHP SDK v4: One-Click Registration & Login

<?php
// Must pass session data for the library to work (only if not already included in your app).
session_start();

// Facebook app settings
$app_id       = '';
$app_secret   = '';
$redirect_uri = '';

// Requested permissions for the app - optional.
$permissions = array(
    'email',
    'user_location',
    'user_birthday'
);

// Define the root directoy.
define( 'ROOT', dirname( __FILE__ ) . '/' );

// Autoload the required files
require_once( ROOT . 'vendor/autoload.php' );

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\GraphUser;

// Initialize the SDK.
FacebookSession::setDefaultApplication( $app_id, $app_secret );

// Initialize the Facebook SDK.
FacebookSession::setDefaultApplication( $app_id, $app_secret );
$helper = new FacebookRedirectLoginHelper( $redirect_uri );

// Authorize the user.
try {
    if ( isset( $_SESSION['access_token'] ) ) {
        // Check if an access token has already been set.
        $session = new FacebookSession( $_SESSION['access_token'] );
    } else {
        // Get access token from the code parameter in the URL.
        $session = $helper->getSessionFromRedirect();
    }
} catch( FacebookRequestException $ex ) {

    // When Facebook returns an error.
    print_r( $ex );
} catch( \Exception $ex ) {

    // When validation fails or other local issues.
    print_r( $ex );
}
if ( isset( $session ) ) {

    // Retrieve & store the access token in a session.
    $_SESSION['access_token'] = $session->getToken();

    $logoutURL = $helper->getLogoutUrl( $session, 'http://your-app-domain.com/logout' );

    // Logged in
    echo 'Successfully logged in! <a href="' . $logoutURL . '">Logout</a>';
} else {

    // Generate the login URL for Facebook authentication.
    $loginUrl = $helper->getLoginUrl();
    echo '<a href="' . $loginUrl . '">Login</a>';
}

Log a User Out

It’s usually not a common practice to make use of the log out feature within the PHP SDK as this will log a user out of Facebook completely, not just your app. So unless you’ve got a specific edge case where you need to do this, it’s not recommended that you use it.

That said, you can log a user out of Facebook in v5 using the getLogoutUrl() method on the FacebookRedirectLoginHelper.

$fb = new Facebook\Facebook([/* */]);

$helper = $fb->getRedirectLoginHelper();

$logoutUrl = $helper->getLogoutUrl('{access-token}', 'http://example.com');
echo '<a href="' . $logoutUrl . '">Logout of Facebook!</a>';

Where http://example.com is the URL the user should be redirected to after logging out.

Retrieve User’s Profile Information

<?php
# Facebook PHP SDK v5: Retrieve User's Profile Information

$res = $fb->get( '/me' );

$user = $res->getGraphObject();

echo $user->getProperty( 'id' );
// 123
Facebook PHP SDK v4: Retrieve User’s Profile Information

<?php
// Retrieve User’s Profile Information
$request = ( new FacebookRequest( $session, 'GET', '/me' ) )->execute();

// Get response as an array
$user = $request->getGraphObject()->asArray();

print_r( $user );

Note: Fields that aren’t set to public must be be requested with an access token with the relevant ‘Extended Profile‘ permissions.

For more information and a full list of possible fields returned, see https://developers.facebook.com/docs/graph-api/reference/v2.0/user.

Get User’s Profile Picture

<?php
# Facebook PHP SDK v5: Get User's Profile Picture

$res = $fb->get( '/me/picture?type=large&redirect=false' );

$picture = $res->getGraphObject();

var_dump( $picture );
Facebook PHP SDK v4: Get User’s Profile Picture

// Get User’s Profile Picture
$request = ( new FacebookRequest( $session, 'GET', '/me/picture?type=large&redirect=false' ) )->execute();

// Get response as an array
$picture = $request->getGraphObject()->asArray();

print_r( $picture );

You can use a list of modifiers to specify the type (e.g. square, small, normal, large), size and whether to send as a JSON array or output as an image. See a list of the available modifiers below:

Modifiers
Name Description Type
redirect The picture edge is a special case, as when requested, it will by default return the picture itself and not a JSON response. To return a JSON response, you need to set redirect=false as a request attribute. This is how to return the fields below. bool
type You use this to get a pre-specified size of picture. enum{square,small,normal,large}
height Restrict the picture height to this size in pixels. int
width Restrict the picture width to this size in pixels. When height and width are both used, the image will be scaled as close to the dimensions as possible and then cropped down. int

For more information and a full list of possible fields returned, see https://developers.facebook.com/docs/graph-api/reference/v2.3/user/picture

Publish to User’s Timeline

A user access token with publish_actions permission can be used to publish new posts.

<?php
# Facebook PHP SDK v5: Publish to User's Timeline

$res = $fb->post( '/me/feed', array(
  'message' => 'I love articles on benmarshall.me!'
));

$post = $res->getGraphObject();

var_dump( $post );
Facebook PHP SDK v4: Publish to User’s Timeline

// Publish to User’s Timeline
$request = ( new FacebookRequest( $session, 'POST', '/me/feed', array(
  'message' => 'I love articles on benmarshall.me!'
) ) )->execute();

// Get response as an array, returns ID of post
$response = $request->getGraphObject()->asArray();

print_r( $response );

// Graph API to publish to timeline with additional parameters
$request = ( new FacebookRequest( $session, 'POST', '/me/feed', array(
    'name' => 'Facebook SDK PHP v4 — a complete guide!',
    'caption' => 'Learn how to easily use the Facebook SDK PHP v4 library.',
    'link' => 'http://www.benmarshall.me/facebook-sdk-php-v4',
    'message' => 'Check out how to integrate Facebook with your website.'
) ) )->execute();

// Get response as an array, returns ID of post
$response = $request->getGraphObject()->asArray();

print_r( $response );

For more information and a full list of additional parameters, see https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed

Retrieve User’s Timeline

A user access token with read_stream permission is required and only posts whose authors have also granted read_stream permission to the app will be shown.

<?php
# Facebook PHP SDK v5: Retrieve User's Timeline

$res = $fb->get( '/me/feed' );

$feed = $res->getGraphObject();

var_dump( $feed );
Facebook PHP SDK v4: Retrieve User’s Timeline

// Retrieve User’s Timeline
$request = ( new FacebookRequest( $session, 'POST', '/me/feed' ) )->execute();

// Get response as an array
$response = $request->getGraphObject()->asArray();

print_r( $response );

There are other edges which provide filtered versions of this edge:

  • /{user-id}/links shows only the links that were published by this person.
  • /{user-id}/posts shows only the posts that were published by this person.
  • /{user-id}/statuses shows only the status update posts that were published by this person.
  • /{user-id}/tagged shows only the posts that this person was tagged in.

All of these derivative edges share the exact same reading structure, however /feed should be used for all publishing purposes.

For more information, see https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed.

Upload a File

$fb = new Facebook\Facebook([/* . . . */]);

$data = [
  'source' => $fb->fileToUpload('/path/to/photo.jpg'),
  'message' => 'My file!',
  ];

$response = $fb->post('/me/photos', $data, '{access-token}');

Upload a Video

If you’re uploading a video, that requires using the videoToUpload() method.

$fb = new Facebook\Facebook([/* . . . */]);

$data = [
  'source'      => $fb->videoToUpload('/path/to/video.mp4'),
  'title'       => 'My video',
  'description' => 'My amazing video!',
  ];

$response = $fb->post('/me/videos', $data, '{access-token}');

For more information, see https://developers.facebook.com/docs/graph-api/reference/video.


Additional Resources

For more information on the Graph API, see https://developers.facebook.com/docs/graph-api/reference/v2.0/. This has a full list of root nodes of the Graph API, with links to the reference docs for each.

RELATED: Facebook SDK PHP v4 & CodeIgniter

If you have any questions or problems, post your comments below. I’ll try to keep this post updated with the latest information and add more API calls later on. Have fun coding!

Author: Ben Marshall

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

48 thoughts on “Facebook PHP SDK v5.x (4.1) — a complete guide!”

      1. Hi, there your code where you get token:
        https://gist.github.com/bmarshall511/cbe0a6faab9fc0505638#file-1457-1-php-L66
        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.

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

Leave a Reply

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