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!

Facebook PHP SDK App Integration

Now that we’ve installed the Facebook PHP SDK, let’s integrate it into a application. Once integrated, we’ll be able to use Facebook login and make requests like retrieving profile info, pictures and more.

Facebook Login Example

Although it’s common to see examples of Facebook Login being implemented in one PHP script, is best to use two separate PHP scripts for more separation and more control over the responses.

In this example, the PHP script that generates the login link is called /login.php. The callback URL that Facebook redirects the user to after login dialog is called /fb-callback.php.

Step 1: Initialize the PHP Facebook SDK

In your project’s root, create a file named login.php.

// Pass session data over. Only needed if not already passed by another script like WordPress.

// Include the required 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.10',

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://example.com/fb-callback.php', $permissions);

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

Replace {app-id} and {app-secret} with the Facebook credentials provided when you created the your Facebook app.

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(

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

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

User permissionDescription
public_profileGives access to a subset of a person’s public profile:

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

See the full list of available permissions.

Step 2: Authenticate

Now that we have the login link, we need to build the script that handles the functionality of the login process (the page Facebook redirects after a user successfully logins to their Facebook account after click the login link above).

// Pass session data over. Only needed if not already passed by another script like WordPress.

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

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

$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} 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();

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';

// Logged in
echo '<h3>Access Token</h3>';

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';

// Validation (these will throw FacebookSDKException's when they fail)
// If you know the user ID this access token belongs to, you can validate it here

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";

  echo '<h3>Long-lived</h3>';

$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');

Step 3: Making Requests

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.


# 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');


// 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();

// 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();

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

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

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

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

$user = $res->getGraphObject();

echo $user->getProperty( 'id' );
// 123
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

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

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

$picture = $res->getGraphObject();

var_dump( $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:

redirectThe 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
typeYou use this to get a pre-specified size of picture.enum{square,small,normal,large}
heightRestrict the picture height to this size in pixels.int
widthRestrict 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

DEPRECATED: Facebook no longer allows apps to post to user’s timeline due to privacy concerns.

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

# 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 );

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.

# Facebook PHP SDK v5: Retrieve User's Timeline

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

$feed = $res->getGraphObject();

var_dump( $feed );

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.

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();

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();


// These all throw a FacebookSDKException

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.

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.

  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();

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

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.

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!

  • Update (March 9, 2018): Minor updates and more simplified instructions provided for the latest version of the Facebook PHP SDK.
  • 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.

1 2


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


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

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

  4. Nabin Bhandari September 3, 2018

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

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

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

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

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

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

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

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

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

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

  15. Awesome content.

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

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


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

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

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

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


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

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

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

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

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

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

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

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

  30. Rahulg FDEV August 3, 2014

    can you tell me how to configure in yii framework

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

  32. Thanks,your code is working fine.

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

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