Facebook API tutorial for PHP

If you look for alternative way to integrate Facebook into your website, you should try the Facebook API. With the Graph API and the Facebook Login feature it’s possible to authenticate users in your web application and upload or post content to a user’s timeline. This Facebook API tutorial is an example how to post a link to the user’s timeline. Check the Facebook API tutorial demo page to see this PHP code in action.

Setting up a Facebook application

Before you’re able to start, it’s necessary to have a Facebook account and a web hosting account. To access the Facebook API you need an App ID and secret. Register your Facebook App via the FaceBook Developer Section. From the top menu select “Apps => Create a New App” to open the pop-up for your app details. Enter the required fields like in the screenshot.

Facebook API PHP Tutorial

After the app is created, click on “Settings” in the left menu. Enter the domain were your web application is hosted or better click the “Add Platform button -> Website” and enter the web application URL (directory) where your web application is located. Keep the browser window open to have access to the App ID and secret on a later moment.

The Facebook SDK for PHP v4.0

In this Facebook API tutorial I use the PHP library or better the Facebook SDK v4.0 for PHP v5.4. You can install the SDK using Composer or download the PHP SDK and upload the files like I did. Extract the ZIP file, rename the directory to “facebook-php-sdk” and upload the directory to your web host (create a new directory first and match the URL you’ve used for your Facebook App).

Facebook API PHP example

Create inside your new directory a new PHP file and add the following code:

Be sure that the path to the autoload.php is correct otherwise the missing PHP libraries will return (only) some nasty error messages. Enter also the Facebook App ID and secret which you can copy from the Facebook App page you’ve created before. The redirect login URL is the URL from your PHP file.

Authentication and authorization

To post a link to a user’s Facebook timeline, the application need an authorization. This is actually a complex function, add this code below the others in your PHP file.

After the application is initiated the helper object is created. This object is used later if a valid Facebook session is messing. The first IF statement is used to check if there is already a valid (PHP) session for the current visitor or user. If the session isn’t valid or empty the helper object is used to create a new session from the login / redirect.

Requests to the Graph API

At the moment that the session is valid, the script is able to post the link to the user’s Facebook timeline. Add this snippet below the other PHP code.

This part of the script does the following: If $session exists, the script stores the object inside a PHP session variable and a new Facebook session object is created. Next we do a request to Facebook that will post the link including the message. Now I create a GraphObject from the response and the script outputs the data to the browser. I use the Facebook message ID for a second request:

This request is used to check if the Facebook message really exists. The GET request is almost the same as the previous POST request. Last but not least we take a look on the code which creates the login URL (place this code below the other).

If the session doesn’t exists, the script returns a login URL which is created from the helper object. Give some attention to the action value I’ve passed to the getLoginUrl method, this value is necessary to post to the users timeline.

That’s all for this tutorial, you can download the tutorial code and check also the code comments for a better understanding. If you understand how it works, you can use this function (a bit modified) as a social feature for the comments form on your WordPress website. 

Resources: Facebook PHP SDK Updated to v4.0.0

Subscribe

Don't miss a future blog post!

Subscribe now and get future blog posts right in your email inbox.

35 Comments

Darian

2014-10-04 8:34 AM Reply

hi
Admin can i know how i can use facebook api to upload picture to the user profile??

    Olaf Lederer

    2014-10-04 4:07 PM Reply

    Check this list of API end points here first. It’s possible to send a photo to the user’s own timeline or photo album. Is this the feature you’re looking for?

Filipe Barros

2014-11-04 4:51 PM Reply

Hi its not working here :/ when i call the php file wich start the API this error appear

Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or ‘(‘ in /home/pmsmm/public_html/fb.php on line 5

    Olaf Lederer

    2014-11-04 5:29 PM Reply

    Hi,

    what is the code on row 5 in your fb.php file?

    Gnik Nalu

    2015-02-09 8:38 PM Reply

    Update your PHP version if you see the ” unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING” error.

      Olaf Lederer

      2015-02-09 9:17 PM

      … and why should the PHP update help? Please explain, no one should update anything because some said so :)

InReal4D

2014-12-11 4:33 PM Reply

Facebook (post) request error: (#200) The user hasn’t authorized the application to perform this action

what ?

    Olaf Lederer

    2014-12-12 9:07 AM Reply

    This is an error created by the Facebook API system. Before you can post to the Facebook user’s time-line, the user has to authorize the application first. Makes sense?

InReal4D

2014-12-12 4:00 PM Reply

How to allow me to use the application?

    Olaf Lederer

    2014-12-12 7:11 PM Reply

    Hi,
    maybe it will help to read the tutorial again, you need to follow all the steps before you can use the tutorial code. The example script is not ready to use, if you didn’t created a valid Facebook app in your account. If you followed all steps and doesn’t work, it’s possible that you didn’t authorized your own app as a regular Facebook user. Note, the Facebook Graph API is a bit complicated and doesn’t provide a lot of information. All you can do is “trial and error” :)

Emily

2015-01-27 8:23 PM Reply

Hi
I have exactly same code, but I keep getting error “Facebkook (post) request error: Invalid parameter”.
Do you know why?

    Olaf Lederer

    2015-01-27 8:51 PM Reply

    Hi Emily,
    Do you followed all steps, including the application you need to create at developer at facebook? It doesn’t work if you only copy the code. Do you know if the error comes from Facebook or your script?

      Emily

      2015-01-27 10:22 PM

      Yes, I did.
      if I only put message, it will work. But if I add link, it won’t work. it just showed “Facebkook (post) request error: Invalid parameter”
      I also want to add images with text. I used $session,
      ‘POST’,
      ‘/me/photos’, array(
      //’link’ => ‘http://uni.edu/’,
      ‘source’ => new CURLFile(‘path/to/file.name’, ‘image/png’),
      ‘message’ => ‘welcome to uni’

      it failed also. errors are ”
      PHP Fatal error: Uncaught exception ‘Facebook\FacebookSDKException’ with message ‘couldn’t open file “path/to/file.name”‘ in D:\Inetpub\wwwroot\gandr\TX_FB_API\facebook-php-sdk-v4-4.0-dev\src\Facebook\HttpClients\FacebookCurlHttpClient.php:150
      Stack trace:
      #0 D:\Inetpub\wwwroot\gandr\TX_FB_API\facebook-php-sdk-v4-4.0-dev\src\Facebook\FacebookRequest.php(248): Facebook\HttpClients\FacebookCurlHttpClient->send(‘https://graph.f…’, ‘POST’, Array)
      #1 D:\Inetpub\wwwroot\gandr\TX_FB_API\app\example.php(84): Facebook\FacebookRequest->execute()
      #2 {main}
      thrown in D:\Inetpub\wwwroot\gandr\TX_FB_API\facebook-php-sdk-v4-4.0-dev\src\Facebook\HttpClients\FacebookCurlHttpClient.php on line 150

      Could do tell me how to post link and images through the app.
      Thanks you so much

Olaf Lederer

2015-01-28 7:40 AM Reply

Hi Emily,
The Graph API is very limited in what you can post, posting an image is not always possible.
You can check the other API systems and maybe you get it working with this one?
https://developers.facebook.com/docs/graph-api/reference/v2.2/post

It’s a lot of testing because there is not so much “real” information available.

mncedisi

2015-02-09 8:19 PM Reply

Hi

i did everything but it doesn’t create a session or redirect

    Olaf Lederer

    2015-02-09 9:19 PM Reply

    Hi,
    at which point do you recognize this problem? Please provide more details and maybe I can help to locate the problem.

MonasteryTech

2015-02-15 11:22 PM Reply

Hi can you tell me how to store the authorization data to MySQL database so that authorization can be done only one time. Furthermore, can you explain how can you save the authorization that the user authorize only one time on a web app and can share and post again and again without having to do the authorization again and again

Regards
MonasteryTech

    Olaf Lederer

    2015-02-16 7:32 AM Reply

    The authorization is based on the Facebook session set in the users browser. Furthermore the user has to accept the app ones to be added to his profile (that are in total two dialog boxes). There is no way to auto post to a user’s Facebook timeline and there will be always a dialog box. This is how this example works. Storing the keys in a database wouldn’t help.

mncedisi

2015-02-17 5:41 PM Reply

Hi
Problem solved, i didn’t destroy the last user session set on my application. thanks

Bostjan Karlic

2015-02-20 12:00 PM Reply

Can you tell me if this aplication use FB API graph 2.xx or still 1.0?

    Olaf Lederer

    2015-02-20 12:53 PM Reply

    I have written this code/tutorial for the PHP SDK (version 4.0), which supports the latest Open Graph API 2.x. The old version 1.0 will have an EOT in April 2015.

mncedisi

2015-02-22 10:23 PM Reply

Hi

I cant post image into Profile Album but my app is granted for ‘user_photo permission’, it gives me this error “(220) Application does not have the capability to make this API call”.

Please help

Mohza

2015-02-24 5:32 AM Reply

Hello there,

I have followed your script and also have create my app on the Facebook developer side. I have put the code until “Authentication and authorization” section. After that, I have put var_dump($session) and I can only see “NULL”. Any idea why?

By the way, what I want to achieve is this. I need to write a small web app in PHP which able to read private messages from inbox of the Facebook Page and also reply to the sender. But I don’t even know the step. I have read several docs in Facebook developer page but I lost, don’t really know where to start. I appreciate if you could give me some general overview of steps that I need to take.

Thanks in advance!

    Olaf Lederer

    2015-03-04 5:56 PM Reply

    Hi Mohza,

    check the developer manual first, the API doesn’t provide a feature for any function on Facebook. Can’t remember me a feature for the personal inbox…

Amit

2015-03-02 1:26 PM Reply

There is error while using $_FILES[“image”][“tmp_name”]. But i want to upload image on user wall plz help me it gives #324( Requires uploaded file error)

    Olaf Lederer

    2015-03-04 5:59 PM Reply

    Hi Amit,
    the tutorial isn’t about a PHP upload, check your own code first to see where the problem is located (test your script step by step)

Mairis

2015-03-12 11:40 AM Reply

Hi, Olaf!

after loging in everithing gets posted to my timline perfectly. After that i get redirected to my php file and this is what i see:

where is the problem?

    Olaf Lederer

    2015-03-12 2:00 PM Reply

    Hi Mairis,

    if you use the code right from the tutorial, than it’s necessary to remove this echo / var_dump() call.

    ';

    This one is used to see that it works, the example file isn’t a full working application or script.

Eltayeb

2015-03-25 4:19 PM Reply

Hello man thx for the tutorial but i have a very weird problem, i did everything as u did and changed nothing but when i run the file it keeps giving me the same “No session, please login.”. it seems i cant get a session :S

    Olaf Lederer

    2015-03-26 1:42 PM Reply

    Do you authorized the session using your own Facebook account?
    The example script is just a demo not an application… if it works on my demo page, the same code should work for you, too.

      Eltayeb

      2015-03-30 5:11 PM

      wt do u mean by “authorized the session using your own Facebook account”

      Olaf Lederer

      2015-04-08 7:40 PM

      That will say, if you run my demo you need to be logged in with you Facebook account and than you have to authorize the application.
      Note the demo/application is just and example how you can implement such a feature in your own application. It’s not a standalone script!

RC76

2015-05-11 3:53 PM Reply

Can you create your own session without being logged in? e.g. I am just trying to post to my own page with php, not from my machine where I am logged in to Facebook.

Is there a way to create my own session in php?

    Olaf Lederer

    2015-05-12 10:10 AM Reply

    My example is about something else and I’m not sure if this is possible. Do you check the API manual? The method you need is different from the one I’ve used for the tutorial. I remember my that I tried something similar for a WordPress site and finally I used a IFTTT recipe :)

Leave a Comment