Facebook PHP SDK — a simple guide!

Written by
Typical Read
2 minutes

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:

[shell]composer require facebook/graph-sdk[/shell]

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:

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

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

56 comments on “Facebook PHP SDK — a simple guide!”.

# Apr 24, 2015

Awesome content.

# Apr 1, 2015

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?

# Jun 17, 2015

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.


# Feb 1, 2015

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.


# Feb 2, 2015

Take a look at https://wordpress.org/support/topic/using-session-in-wordpress Should help with the session issue in WordPress.


# Dec 16, 2014

for developing facebook can i using localhost for testing?

# Dec 16, 2014



# Dec 22, 2014

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?


# Nov 26, 2014

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.

Dimitris Sarmis

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

# Jan 30, 2015

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.


# Nov 24, 2014

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.


# Jan 30, 2015

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


# Oct 27, 2014

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?

# Nov 18, 2014

Can I see your code?


# Oct 11, 2014


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

# Feb 4, 2015

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


# Sep 18, 2014

Really awesome content, it helped me allot, thanks!

# Aug 19, 2014

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?

# Aug 25, 2014

If your app is on Facebook Canvas, use the getSession() method on https://developers.facebook.com/docs/php/FacebookCanvasLoginHelper" target="_blank" rel="nofollow noopener noreferrer ugc">FacebookCanvasLoginHelper to get a FacebookSession for the user.

Thinh Nguyen

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

# Aug 25, 2014

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 https://developers.facebook.com/docs/apps/test-apps/" target="_blank" rel="nofollow noopener noreferrer ugc">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.


# Aug 15, 2014

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?

# Aug 25, 2014

It just depends on the app you’re building. The important part is it needs to included before any output is sent.


# Aug 13, 2014

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

# Feb 4, 2015

Gonna need a little more info than that to help. Can you provide me the code or error you’re seeing?


# Aug 4, 2014

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 🙂

# Aug 25, 2014

That code was a little outdated. Just updated the post and example code with the latest. Should make more sense now.

Rahulg FDEV

# Aug 3, 2014

can you tell me how to configure in yii framework

# Aug 3, 2014

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

# Aug 25, 2014

Looks like you’re redefining a namespace. Download the demo files to see an example.


# Jul 25, 2014

Thanks,your code is working fine.

# Jul 24, 2014

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

Niko Jojo

# Jul 22, 2014

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

# Aug 25, 2014

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.

# Aug 31, 2014

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.

# Aug 31, 2014

Problem solved. I was wrong with trying to get token without facebook response…


# Jun 26, 2017

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.


# Mar 14, 2017

v good!

Join the conversation.

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

All comments posted on 'Facebook PHP SDK — a simple guide!' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

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.