As a guy who prefers to use modern stuff like Node.js instead of crappy old PHP, I´m not really a fan of the Facebook PHP SDK. But sometimes you just need to use it – so here´s a basic tutorial for the current Facebook PHP SDK, they bumped it up a major version so i had to try it. It´s a bit weird that they call it “v4-5.0” though. I knew it would be a problem to use the tag “facebook-php-sdk-v4” on github…
Btw, the basic stuff from my older blogpost about the Facebook PHP SDK 4.0 still applies and you should definitely read it – especially the part about securing your API calls with appsecret_proof.
Installing the Facebook PHP SDK
I don´t want to install Composer for the few things i do with PHP, so i downloaded the SDK manually. You can do that here: https://developers.facebook.com/docs/php/gettingstarted/5.0.0#install-manually
Login, Redirection and User Token
I created a folder called “/phpsdk5” for testing and put in the source only, and i am only using the FacebookRedirectLoginHelper this time, because it is the most common one. Here is the code for authorizing and getting basic data:
index.php
<?php require_once __DIR__ . '/phpsdk5/autoload.php'; session_start(); $fb = new Facebook\Facebook([ 'app_id' => 'APP-ID', 'app_secret' => 'APP-SECRET', 'default_graph_version' => 'v2.4', 'default_access_token' => isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : 'APP-ID|APP-SECRET' ]); try { $response = $fb->get('/me?fields=id,name'); $user = $response->getGraphUser(); echo 'Name: ' . $user['name']; exit; //redirect, or do whatever you want } catch(Facebook\Exceptions\FacebookResponseException $e) { //echo 'Graph returned an error: ' . $e->getMessage(); } catch(Facebook\Exceptions\FacebookSDKException $e) { //echo 'Facebook SDK returned an error: ' . $e->getMessage(); } $helper = $fb->getRedirectLoginHelper(); $permissions = ['email', 'user_likes']; $loginUrl = $helper->getLoginUrl('http://facebook.devils-heaven.com/login-callback.php', $permissions); echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
It´s a lot easier now with the PHP SDK 5.0. First, we initialize the SDK with the Access Token – if no Token is set, we fall back to the App Access Token. Then we try to make a request to the /me endpoint. If it goes through, we show the name of the user. If not, the RedirectLoginHelper will get used to generate a Login URL that redirects to login-callback.php.
login-callback.php
<?php require_once __DIR__ . '/phpsdk5/autoload.php'; session_start(); $fb = new Facebook\Facebook([ 'app_id' => 'APP-ID', 'app_secret' => 'APP-SECRET', 'default_graph_version' => 'v2.4', 'default_access_token' => 'APP-ID|APP-SECRET' ]); $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)) { // Logged in! $_SESSION['facebook_access_token'] = (string) $accessToken; } elseif ($helper->getError()) { // The user denied the request } header('Location: index.php');
This script just stores the Access Token and redirects to login.php. We can use an App Access Token as default, because if the user gets to this script he most likely will not have an active Token. After initialization it´s just about getting the Access Token with the Helper (getAccessToken), storing it in the session and redirecting to index.php.
I´m not entirely sure if that´s the correct way because the official docs are still a bit shaky with the latest PHP SDK, but it works 🙂 You don´t need all those error checking routines, but i suggest using them for logging errors in your system.
Extending the Token
In many scenarios you would want to extend the User Token, and it´s quite easy with the PHP SDK. Just add two lines right before storing the Token in a session in your login-callback.php file:
if (isset($accessToken)) { // Logged in! $oAuth2Client = $fb->getOAuth2Client(); $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken); $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken; } elseif ($helper->getError()) { // The user denied the request } header('Location: index.php');
As always, if you got any questions, use the comments. Don´t forget to like/share my article if it helped you
Please, you can share your source code. Thanks.
I tried but when i click “Log in with Faceook”, i have recieved message from fb
“Given URL is not permitted by the Application configuration: One or more of the given URLs is not permitted by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.”
that is a well known error, please search on stackoverflow for that one. you will find plenty of answers, it´s most likely a problem with your app settings.
go to “developers.facebook.com”, find your app, then in the App Settings Section of your dashboard you will find “App Domains”.
Hope it helped 🙂
all the source code you need is in the article, you just need to copy and understand it 🙂
Thanks, I done. But you can teach me how to get friends.
I write below:
$friends = $fb->get(‘/me/friends’);
foreach ($friends[‘data] as $value) {
echo ‘ID:’ .$value[‘id’]. ”;
echo ‘Name:’ .$value[‘name’]. ”;
}
And this is message of error:
Notice: Undefined index: friends in C:\xampp\htdocs\phpsdk5\phpsdk5\GraphNodes\Collection.php on line 201
Friends:
Fatal error: Cannot use object of type Facebook\FacebookResponse as array in C:\xampp\htdocs\phpsdk5\index.php on line 25
And “permission” i added “user_friends”.
This is code:
$permissions = [’email’, ‘user_likes’, ‘user_friends’];
you don´t get an array with that function, check out the docs: https://developers.facebook.com/docs/reference/android/current/class/GraphResponse/
I have a problem on the landingpage after login. When making the first request to the API I receive the error “Graph returned an error: Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.. The weird things is that this does not happen when I navigate to the page via typing the url in the address bar. Only when I access the site via a hyperlink
i´m afraid that´s not detailed enough to help you. feel free to post your question on stackoverflow, including the relevant code parts, and post the link here.
He Andreas. Thank you for taking the time to reply. I tried asking the question on stackoverflow (http://stackoverflow.com/questions/31698432). So far no fix. What part of the code would be helpfull to go through? You can access my login page at http://www.youddress.com/foundation, with the login placed on the top right. It won’t work, but somehow after a page refresh it does. hope this helps! thanks again
I think the problem lies with setting the default access token. In all tutorials I see “$fb->setDefaultAccessToken($accessToken);” however this gives me the error “The default access token must be of type “string”. So i changed it to $fb->setDefaultAccessToken((string) $accessToken); but I get the idea that somehow the session does not store this token. Could I be right?
well, the token always must be a string, yeah. if you need to cast it to make it work, it´s not a string before the cast.
Somehow I can’t see why this works in some cases, but not when I accessed through a link. I guess I’ll just keep trying. thanks for the effort
Eureka. It was my $loginUrl. I did not notice I did not add www.
what the problim
back
Graph returned an error: This authorization code has been used. !!
use google to search for that error, it is very well known and subject of many stackoverflow threads
It works and i can handle with name, first name and many other stuff. But how can I get the user picture URL?
$user[‘picture’][‘data’][‘url’] <– This is not working. How can I navigate trough $user?
var_dump($user) > make sure it includes all the information you need. check out the changelog for v2.4 about “declarative fields” too: https://developers.facebook.com/docs/apps/changelog#v2_4
Hi, thanks for tutorial. Can you help me, how i get the user email ?
you get the user mail by authorizing with the email permission, and you have to use /me?fields=email to get the email in the response, see changelog for v2.4: https://developers.facebook.com/docs/apps/changelog#v2_4
Andrew, Thanks for the response, I’ve tried but still can not get the user’s email. Here’s the code I use:
$response = $fb->get(‘/me?fields=email,name,id’);
$user = $response->getGraphUser();
echo ‘Name: ‘ . $user[‘name’] . “”;
echo ‘id: ‘ . $user[‘id’] . “”;
echo ’email: ‘ . $user[’email’];
debug the response, there´s surely an error message if it does not work
sir how to Post a status on my friends timeline using the code
that´s not possible at all, for very good reasons. it would pretty much always be spam.
What if you would have a complex site with component and multiple Facebook buttons on 1 page. So assume `$facebook->getRedirectLoginHelper()` is called multiple times for different buttons.
In that case only the last button works because it sets every time a new CSRF token when you call it. Do you any solutions for that?
Kind regards,
Wouter
to be honest, i am not sure why anyone would place more than one login button… 😉
How can I get my page’s feed? Is there a way to do that? I just want to get a list of the most recent post of my Facebook page in order to show them into my website !
thank you
The API endpoint for that is /page-id/feed, just take a look at the official docs: https://developers.facebook.com/docs/graph-api/reference/v2.5/page/feed
Please, can you show me an example or send it by e-mail? i really need the right way to do that but i’m a beginner.. i just need a better explanation.. I have already used your examples and they work fine but i don’t know how to add the rest of the code to show my page feed.
Thank you!
there is example code in the official docs, check out the link i posted.
Thanks a lot for your tutorial ! I am not sure to understand everything… (I’m french 😉
I have this error :
Fatal error: Uncaught exception
I don’t know what to do with my facebook-access-token. The error is the same whether i paste it or not.
Thanks for your advices.
Regards,
Cynthia
that error is too unspecific to help you in a serious way, i´m afraid. you need to activate error logging for your server, and you need to debug where it is happening. Btw, i wrote another article about the Access Tokens: https://devils-heaven.com/facebook-access-tokens/
Hi, i am wondering will it work with the call of ‘me/feed’?
I tried but mostly it gives an empty array.
emtpy array means that you either have no posts on your wall, or you did not authorize with the user_posts permission (or both).
It’s better to provide a working samples of yours or even the editable one.
my code is always tested and worked when i wrote the article, all code put together should be a working example. but i should put a working example online where people can test and login, will do that asap.
This code is not right. There needs to be conditional “if”‘s before the try/catch block. Now it just open up holes for errors.
please explain why it opens up holes for errors? it´s a simple tutorial explaining how it works in general, of course there´s more work to it if you take it serious 😉
Hello ,
Can you please give me any example to get events of a users using Facebook SDK 5?
Thanks in advance
there is example code in the docs: https://developers.facebook.com/docs/graph-api/reference/v2.5/user/events/
Is it possible to fetch the likes and comments from the posts on a feed, can’t seem to find anything in facebook dev docs
there are likes and comments endpoints for a post id: https://developers.facebook.com/docs/graph-api/reference/v2.6/post
The code logs me in then leaves me at login-callback.php with no confirmation of being logged in. Just blank whiteness. Can i echo something to confirm i’m logged in?
Paul
make sure you activated error logging in php and debug your code. check your browser console for errors too.
Hello sir,
Can you please show us a complete source code of a little FB app ?
For example after the user authorizes the app, the app generate some very basic image [applying some basic image filter or effects on the profile photo] and shows a share dialog to the user to post the image on his own timeline.
Thanks in advance.
Regards
hi,
sorry, but i don´t work for free. i am up for hiring if you need an app done though 😉 – although, there are some limitations on that one, it´s not possible to post a photo with a simple share dialog. you would need to authorize the user to post a photo.
Hi, just trying it out, a few questions
Is the following supposed to be replaced with the values or is it as is?
‘APP-ID|APP-SECRET’
Is the header line supposed to go back to the login.php ?
that is YOUR app id and YOUR app secret, of course you need to replace it with your own values.
yes, the header line redirects to login.php. if it doesn´t, you most likely don´t get to that line.
Hello, I am using facebook PHP SDK v5 with your code. but I am still getting below error. So can you please give me advice ?
Fatal error: Call to undefined function hash_equals() in D:\xampp\htdocs\facebookpostupdate\src\Facebook\Helpers\FacebookRedirectLoginHelper.php on line 246
Thank you!
which PHP version are you using? try upgrading it. i believe hash_equals needs PHP 5.6+.
I have little problem. I couldnt find to usage i want.
$linkData = [
‘link’ => $url,
‘message’ => $message
];
that is parameter of url post. But i want to use custom thumbnail image.
I find that;
https://developers.facebook.com/docs/graph-api/reference/v2.7/user/feed
This says i can use picture, name, caption and description of link. But how can i use ? Cause link value is string its not array. When i tried to code like that;
$linkData = [
‘link’ => $url,
‘picture’ => $image,
‘message’ => $message
];
It didnt work. How can i use ?
Thanks in advance.
Thanks so much for the tutorial. Your explanation was very help because i had same code but was implementing in a wron way. Thanks once again. Just before i leave, i’d like to know how i can store the information i get on my local db and pull same information whenever the user views their profile/account on my website.
that is a bit too broad, i´m afraid. you should go through some basic mysql tutorials for that. there are hundreds of them….if mysql is your database, that is.
Thanks for this great tuto, but I’m still stuck.
my code:
$fb = new Facebook\Facebook([
‘app_id’ => ‘123456789012345’,
‘app_secret’ => ‘ababababababababababababababab’,
‘default_graph_version’ => ‘v2.8’,
‘default_access_token’ => ‘123456789012345|ababababababababababababababab’
]);
$response = $fb->get(‘/me?fields=id,name’);
This raises an exception with message “An active access token must be used to query information about the current user”
Any idea/suggestion ?
you can´t use an app token to get userdata, you need to use a user token. read this article to find out how to get a user token: https://devils-heaven.com/facebook-access-tokens/
Thank you for the helpful article. 😉
Hello. I’m using this php sdk and have question.
public function deleteComment(Request $request)
{
try {
$this->fb->delete(‘/’ . $request->get(‘id’));
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo ‘Message: ‘ . $e->getMessage();
$previousException = $e->getPrevious();
// Do some further processing on $previousException
exit;
}
// FBM::where(‘comment_id’, $request->get(‘id’))->delete();
}
When i post comments from my app, all ok, i can delete them, but when i post comment from browser and try to delete it from app i get:
(#200) Users can only delete their own comments published by the same app
Please, answer me and help my mind 🙂
Will waiting your answer.
Regards!
App works at test version, so you can’t get comments.
Sorry, to comment above:
i use $permissions = [‘public_profile’, ’email’, ‘user_likes’, ‘user_posts’, ‘publish_actions’, ‘publish_pages’, ‘publish_actions’, ‘publish_pages’, ‘manage_pages’];
Hello, i use Facebook SDK for PHP (v5). I can write and delete comments from my web app. When i publish comments from my browser i can’t delete them from my app. On Tester Users all works fine. I added for second account tester role. Is this problem in permissions ? I have this:
$permissions = [‘public_profile’, ’email’, ‘user_likes’, ‘user_posts’, ‘publish_actions’, ‘publish_pages’, ‘publish_actions’, ‘publish_pages’, ‘manage_pages’];
Error:
FacebookResponseException in FacebookResponseException.php line 126:
(#200) Users can only delete their own comments published by the same app
hi! i am not sure what to tell you, to be honest. the error message is very clear, you can only delete comments made by your app. you can´t delete comments made in the browser, it is just not possible.
Hi Andreas,
I have used your code and still facing this error:Graph returned an error: Invalid OAuth access token. What did I miss????
Below is my code with cakephp:
————————————————————-
public function facebook_login()
{
require_once ‘/Facebook-SDK5/autoload.php’;
Configure::load(‘facebook’);
$appId=Configure::read(‘Facebook.appId’);
$app_secret=Configure::read(‘Facebook.secret’);
session_start();
$facebook = new Facebook\Facebook([
‘app_id’ => $appId,
‘app_secret’ => $app_secret,
‘default_graph_version’ => ‘v2.8’,
‘display’=>’popup’,
‘default_access_token’ => isset($_SESSION[‘facebook_access_token’]) ? $_SESSION[‘facebook_access_token’] : $appId|$app_secret]);
try {
$response = $facebook->get(‘/me?fields=id,name’);
$user = $response->getGraphUser();
echo ‘Name: ‘ . $user[‘name’];
exit; //redirect, or do whatever you want
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo ‘Graph returned an error: ‘ . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo ‘Facebook SDK returned an error: ‘ . $e->getMessage();
}
$helper = $facebook->getRedirectLoginHelper();
$permissions = [’email’, ‘public_profile’];
$loginUrl = $helper->getLoginUrl(‘https://www.mywebsite.com/facebook_connect’, $permissions);
// echo ‘Log in with Facebook!‘;
$this->redirect($loginUrl);
}
——————————————————————————————-
debug the access token in the debugger and see what you get: https://developers.facebook.com/tools/debug/accesstoken/
How can I get the access token? what is code to allow cake PHP print the access token? what is the variable that have the access token?
At least, does my code look fine?
> $_SESSION[‘facebook_access_token’]
you could try debugging that one. get familiar with all the different access tokens first: https://devils-heaven.com/facebook-access-tokens/
Andres,
I am using echo $_SESSION[‘facebook_access_token’]; and the output is nothing. no single value (null), what is wrong in my code very strange!. Can you check? APP ID and Secret are fine. I do not even get the facebook login pop up!
I am still using SDK3 and it is working fine on the 2nd attempt to login, the first try no token at all, do you know why?
you are not using a popup, you are using a redirection. do you not even get redirected? what´s the var_dump of your login url?
I have ‘display’=>’popup’, so it is pop up?
How do I get the var_dump?
i believe you are mixing login with the js sdk and login with the php sdk…make sure you know what´s happening. your code looks like you are ONLY using the php sdk, there is no popup for that, only redirection.
Andreas,
There is a pop up to login to Facebook where users can enter facebook user email and passsword and then redirects, it is not working with the SDK5. Now, I am getting “Facebook SDK returned an error: Failed to connect to graph.facebook.com port 443: Connection timed out”
that popup is from the js sdk, NOT the php sdk. again, don´t mix those. make sure you know the difference, it´s very important.
Thanks for this, but it results in a blank screen. No server or console errors displayed, and
echo ‘Name: ‘ . $user[‘name’]; never displayed. Also, my app isn’t logged into or at least isn’t listed in Facebook => Settings => Apps. Something missing?
blank screen usually means that there is something wrong on the server. make sure to look at the error logs. also, you are definitely not logged in if it is not listed. hard to say more without looking at the code, you should create a question on stackoverflow.
Hi, just trying to implement Facebook login using PHP SDK. Created an facebook app but when it redirect to the facebook login page, gives an error “Domain not added in App”.
Although i have added my domain in app basic settings.