Facebook PHP SDK 5.0 Tutorial

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 :)

74 thoughts on “Facebook PHP SDK 5.0 Tutorial”

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

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

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

        1. And “permission” i added “user_friends”.
          This is code:
          $permissions = [’email’, ‘user_likes’, ‘user_friends’];

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

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

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

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

      1. 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’];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  16. Sorry, to comment above:
    i use $permissions = [‘public_profile’, ’email’, ‘user_likes’, ‘user_posts’, ‘publish_actions’, ‘publish_pages’, ‘publish_actions’, ‘publish_pages’, ‘manage_pages’];

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

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

  18. 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);
    }

    ——————————————————————————————-

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

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

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

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

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

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

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

Leave a Comment

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.