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:


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.


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:

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

    • DoVuQuocViet says:

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

      • Dan says:

        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. Christiaan says:

    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

        • Christiaan says:

          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?

  2. Simon says:

    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?

  3. Wouter says:

    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,

  4. Manuel says:

    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

  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.



    • 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. Gexolio says:

    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.

  7. Diego says:

    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. Paul K says:

    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?


  9. Sourav says:

    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.

    • 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. Andrew says:

    Hi, just trying it out, a few questions

    Is the following supposed to be replaced with the values or is it as is?

    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.

  11. hardik says:

    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. Hex4d0r says:

    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;

    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. Timmy says:

    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. Xavier says:

    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. Alex says:

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

    App works at test version, so you can’t get comments.

  16. Alex says:

    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. Alex says:

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

    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.

  18. Dani says:

    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’;




    $facebook = new Facebook\Facebook([
    ‘app_id’ => $appId,
    ‘app_secret’ => $app_secret,
    ‘default_graph_version’ => ‘v2.8’,
    ‘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!‘;



  19. Dani says:


    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?

    • 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. Dani says:


    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?

    • 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. Manish says:

    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 Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.