Simple Facebook PHP SDK 4 tutorial

-

UPDATE (5/2017): This version of the Facebook PHP SDK (v4) is no longer supported. I'll leave this post up, in case the sample code is useful. You can upgrade your version 4 code to version 5 by following this tutorial.

The Getting Started guide for Facebook SDK 4 is only useful once you have the SDK up and running. But if you don't have Composer installed then it's not immediately clear how to get the SDK working. Here is a quick start guide.

We are going to make a Facebook app that displays the user's most recently uploaded photo. Try out the working example (UPDATE: defunct).

Including the classes

First things first: you need to download the SDK from Github and put the folder "Facebook" (found in facebook-php-sdk-v4-4.0-dev\src) in the same folder as your app.

The beginning of your Facebook app will start the session with session_start() and then require and use all of the necessary classes and namespaces respectively.

<?php
session_start();

require_once('Facebook/FacebookSession.php');
require_once('Facebook/FacebookRedirectLoginHelper.php');
require_once('Facebook/FacebookRequest.php');
require_once('Facebook/FacebookResponse.php');
require_once('Facebook/FacebookSDKException.php');
require_once('Facebook/FacebookRequestException.php');
require_once('Facebook/FacebookAuthorizationException.php');
require_once('Facebook/GraphObject.php');
require_once('Facebook/HttpClients/FacebookCurl.php');
require_once('Facebook/HttpClients/FacebookHttpable.php');
require_once('Facebook/HttpClients/FacebookCurlHttpClient.php');
require_once('Facebook/Entities/AccessToken.php');
require_once('Facebook/GraphUser.php');

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\GraphUser;
?>

Obviously you will need to get an app ID and secret from Facebook Developer.

You can initialize the Facebook SDK anytime before you start making calls:

<? 
$app_id = 'YOUR_APP_ID';
$app_secret = 'YOUR_APP_SECRET';
FacebookSession::setDefaultApplication($app_id, $app_secret);
?>

Now I set up some appropriate formatting to the page before we add in the actual UI.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Facebook SDK example</title>
</head>
<body>

</body>
</html>

Logging the user in

So now we need a login button for the user; this code needs to go in the body. A slight variation of what's shown in the documentation:

<?
$helper = new FacebookRedirectLoginHelper(YOUR_APP_URL, $app_id, $app_secret);
try {
    $session = $helper->getSessionFromRedirect();
}
catch(FacebookRequestException $ex) { } 
catch(\Exception $ex) { }

$loggedIn = false;

if (isset($session)){
if ($session) {
    $loggedIn = true;
    try {
      // Logged in
      
    } catch(FacebookRequestException $e) {
        
        echo "Exception occured, code: " . $e->getCode();
        echo " with message: " . $e->getMessage();
        
    }   
    
}
}
if (!$loggedIn){
  $loginUrl = $helper->getLoginUrl();
  echo "Login";
}
?>

We check to see if the user is logged in, and if not, we check for errors/display the login URL. Now the code is ready to make calls to the Graph API.

Before we do that, however, we need to request the permission to view the user's photos. So we change the line:

$loginUrl = $helper->getLoginUrl();

to:

$loginUrl = $helper->getLoginUrl(array('user_photos'));

Making calls with the Graph API

We want the user's photos. According to the Graph API documentation, we can get this with /{user-id}/photos/uploaded, or in this case, /me/photos/uploaded.

So we add our API call within the if statement:

try {
  // Logged in
  $user_photos = (new FacebookRequest(
    $session, 'GET', '/me/photos/uploaded'
  ))->execute()->getGraphObject(GraphUser::className());     
}

and we convert the response to an array:

$user_photos = (new FacebookRequest(
  $session, 'GET', '/me/photos/uploaded'
))->execute()->getGraphObject(GraphUser::className());

$user_photos = $user_photos->asArray();

Now we can view the result with print_r:

print_r($user_photos);

and it becomes clear that we need $user_photos["data"][0]->{"source"}.

$pic = $user_photos["data"][0]->{"source"};
//print_r($user_photos);
echo "<img src='$pic' />";

Done. Here is a copy of the entire code:

<?php
session_start();
 
require_once('Facebook/FacebookSession.php');
require_once('Facebook/FacebookRedirectLoginHelper.php');
require_once('Facebook/FacebookRequest.php');
require_once('Facebook/FacebookResponse.php');
require_once('Facebook/FacebookSDKException.php');
require_once('Facebook/FacebookRequestException.php');
require_once('Facebook/FacebookAuthorizationException.php');
require_once('Facebook/GraphObject.php');
require_once('Facebook/HttpClients/FacebookCurl.php');
require_once('Facebook/HttpClients/FacebookHttpable.php');
require_once('Facebook/HttpClients/FacebookCurlHttpClient.php');
require_once('Facebook/Entities/AccessToken.php');
require_once('Facebook/GraphUser.php');
 
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\GraphUser;

$app_id = 'YOUR_APP_ID';
$app_secret = 'YOUR_APP_SECRET';

FacebookSession::setDefaultApplication($app_id, $app_secret);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Facebook SDK example</title>
</head>
<body>
<?

$helper = new FacebookRedirectLoginHelper("https://www.apptic.me/blog/facebook-sdk-test.php", $app_id, $app_secret);
try {
    $session = $helper->getSessionFromRedirect();
}
catch(FacebookRequestException $ex) { } 
catch(\Exception $ex) { }

$loggedIn = false;

if (isset($session)){
    if ($session) {
        $loggedIn = true;
        try {
          // Logged in
          
          $user_photos = (new FacebookRequest(
            $session, 'GET', '/me/photos/uploaded'
          ))->execute()->getGraphObject(GraphUser::className());
          $user_photos = $user_photos->asArray();
          $pic = $user_photos["data"][0]->{"source"};
          //print_r($user_photos);
          echo "<img src='$pic' />";
        } catch(FacebookRequestException $e) {
            echo "Exception occured, code: " . $e->getCode();
            echo " with message: " . $e->getMessage();
        }   
    }
}
if (!$loggedIn){
  $loginUrl = $helper->getLoginUrl(array('user_photos'));
  echo "<a href='$loginUrl'>Login";
}
?>
</body>
</html>

Conclusion

Again, here is a link to the working example: https://www.apptic.me/blog/facebook-sdk-test.php

Feel free to use this code as a starting point for building your own Facebook app. Let me know if you found it useful!

Edit (10/23/2014): User sessions

A commenter pointed out that it was inconvenient for the user to log in every time the page refreshes. I agree.

Along with your require_once calls and your use statements, add:

require_once('Facebook/GraphSessionInfo.php');
use Facebook\GraphSessionInfo;

Then you need to replace:

try {
    $session = $helper->getSessionFromRedirect();
}
catch(FacebookRequestException $ex) { } 
catch(\Exception $ex) { }

$loggedIn = false;

if (isset($session)){
    if ($session) {
        $loggedIn = true;
        try {
          // Logged in
          
          $user_photos = (new FacebookRequest(
            $session, 'GET', '/me/photos/uploaded'
          ))->execute()->getGraphObject(GraphUser::className());

with:

if (isset($_SESSION['fb_token'])) {
  // use a saved access token - will get to this later
  $session = new FacebookSession($_SESSION['fb_token']);
    try {
      if (!$session->validate()) {
        $session = null;
      }
    } 
    catch (Exception $e) { $session = null; }
} else {
    try {
        $session = $helper->getSessionFromRedirect();
    }
    catch(FacebookRequestException $ex) { } 
    catch(\Exception $ex) { }
}

$loggedIn = false;

if (isset($session)){
    if ($session) {
        $loggedIn = true;
        try {
          // Logged in
          $_SESSION['fb_token'] = $session->getToken();
          
          $user_photos = (new FacebookRequest(
            $session, 'GET', '/me/photos/uploaded'
          ))->execute()->getGraphObject(GraphUser::className());

And you're done. There aren't many changes. We added the GraphInfoSession class, then saved the user session after login.

Tags: facebook sdk php tutorial sdk4 simple example permissions

See also: Using custom domains with AWS Elastic Beanstalk

Back to all posts

Neel Somani

About the Author

Neel Somani, a student at the University of California, Berkeley, is the founder of Apptic LLC. In addition to computer science, he's interested in philosophy and entrepreneurship. You can follow him on LinkedIn and Twitter.

comments powered by Disqus