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.

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:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

session_start();

require_once'facebook-php-sdk/autoload.php';

useFacebook\FacebookSession;

useFacebook\FacebookRequest;

useFacebook\GraphUser;

useFacebook\FacebookRequestException;

useFacebook\FacebookRedirectLoginHelper;

$api_key='FACEBOOK_APP_ID';

$api_secret='FACEBOOK_APP_SECRET';

$redirect_login_url='http://www.yoursite.com/somefolder/file.php';

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.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

/initialize your app using your key andsecret

FacebookSession::setDefaultApplication($api_key,$api_secret);

// create a helper opject which is needed to create a login URL

// the $redirect_login_url is the page a visitor will come to after login

$helper=newFacebookRedirectLoginHelper($redirect_login_url);

// First check if this is an existing PHP session

if(isset($_SESSION)&&isset($_SESSION['fb_token'])){

// create new session from the existing PHP sesson

$session=newFacebookSession($_SESSION['fb_token']);

try{

// validate the access_token to make sure it's still valid

if(!$session->validate())$session=null;

}catch(Exception$e){

// catch any exceptions and set the sesson null

$session=null;

echo'No session: '.$e->getMessage();

}

}elseif(empty($session)){

// the session is empty, we create a new one

try{

// the visitor is redirected from the login, let's pickup the session

$session=$helper->getSessionFromRedirect();

}catch(FacebookRequestException$e){

// Facebook has returned an error

echo'Facebook (session) request error: '.$e->getMessage();

}catch(Exception$e){

// Any other error

echo'Other (session) request error: '.$e->getMessage();

}

}

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.

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

if(isset($session)){

// store the session token into a PHP session

$_SESSION['fb_token']=$session->getToken();

// and create a new Facebook session using the cururent token

// or from the new token we got after login

$session=newFacebookSession($session->getToken());

try{

// with this session I will post a message to my own timeline

$request=newFacebookRequest(

$session,

'POST',

'/me/feed',

array(

'link'=>'www.finalwebsites.com/facebook-api-php-tutorial/',

'message'=>'A step by step tutorial on how to use Facebook PHP SDK v4.0'

)

);

$response=$request->execute();

$graphObject=$response->getGraphObject();

// the POST response object

echo'<pre>'.print_r($graphObject,1).'</pre>';

$msgid=$graphObject->getProperty('id');

}catch(FacebookRequestException$e){

// show any error for this facebook request

echo'Facebook (post) request error: '.$e->getMessage();

}

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:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

if(isset($msgid)){

// we only need to the sec. part of this ID

$parts=explode('_',$msgid);

try{

$request2=newFacebookRequest(

$session,

'GET',

'/'.$parts[1]

);

$response2=$request2->execute();

$graphObject2=$response2->getGraphObject();

// the GET response object

echo'<pre>'.print_r($graphObject2,1).'</pre>';

}catch(FacebookRequestException$e){

// show any error for this facebook request

echo'Facebook (get) request error: '.$e->getMessage();

}

}

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.

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”

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

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

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.

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.

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

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!

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