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.
56 comments on “Facebook PHP SDK — a simple guide!”.
# Feb 10, 2020
Hi Ben, i am upgrading Facebook PHP SDK from Version 3.2.1 to Version 5.7.0 to one of my FB canvas app, First what i did was, i analysed how the existing implementation on V 3.2.1, so i have replaced all those methods with the equivalent method on V5.7.0, after all the implementation, my game is loading fine after few minutes it started reloading on its own.. it kept reloading. looks like authentication issue.. i found out that i am getting user_id sometime, but sometime the user_id is returning null, what could be the problem.. i am new to PHP. do i need to store the user_id in $SESSION[] ?. whether PHP SDK 5.7.0 handles native PHP SESSION on its own? i am looking forward to hear from you.
# Jul 2, 2019
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.
Thanks
# Jun 24, 2019
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.
# Oct 7, 2018
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:
$tokenMetadata->validateAppId(YOU_APP_ID);
now the error doesnt appear.
Hope it might usefull to anyone
# Sep 3, 2018
how to get users facebook page and me/accounts/feeds
# Apr 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!
# Feb 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
# Jan 26, 2018
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.
# Jan 23, 2018
Good article!
Great help to me, Thank you.
# Jun 12, 2017
Nice tutorial.how can i also get a facebook user history??please any help
# Jun 10, 2017
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.
# Jun 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!!!!!!
# Jan 25, 2017
Hi Ben,
Thank you for your very detailed article. It helped me quickly rewrite my old API using code. =)
# Jan 11, 2017
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();
}
# May 5, 2015
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’
# Jun 17, 2015
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?
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.