PHP Code Examples

In the Getting Started Guide you learned how to get your name from the Facebook Graph. In this guide, you will learn how to ask for a new permission to get private data and how to get your Facebook posts.

Before You Start

You will need:

Get My Hometown

In this example you will be getting data from a UserNode field, /me?fields=hometown (this represents the person who requested the access token), with a User access token and the user_hometown permission.

To find data using a Facebook User ID replace "/me" with your User ID, for example, /499633188.

Sample index.php File

<!DOCTYPE html>
<html>
<head><title>My Hometown </title></head>

<body>

<h1>Get My Name and Hometown from Facebook</h1>

<?php


require_once __DIR__ . '/vendor/autoload.php'; 

$fb = new \Facebook\Facebook([
  'app_id' => '{your-app-id}',           //Replace {your-app-id} with your app ID
  'app_secret' => '{your-app-secret}',   //Replace {your-app-secret} with your app secret
  'graph_api_version' => 'v5.0',
]);

try {
      // Get your UserNode object with fields name and hometown, replace {access-token} with your token
  
$response = $fb->get('/me?fields=name,hometown', '{access-token}');

} catch(\Facebook\Exceptions\FacebookResponseException $e) {
        // Returns Graph API errors when they occur
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
        // Returns SDK errors when validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$me = $response->getGraphUser();

       //All that is returned in the response
echo 'All the data returned from the server: ' . $me;

       //Pick out my name
echo 'My name is ' . $me->getName();

       //Pick out my hometown
$hometown = $me->getHometown();
$hometown_name = $hometown->getName();
echo 'My hometown is ' . $hometown_name;

?>

</body>

Get My Feed and Messages

In this example we are getting data from an edge, /{user-id}/feed, with a User access token and user_posts permissions. The first output is basically a dump of all data returned from your feed. The second output is individual messages with the message ID from your feed.

If an ID has no message field, it might be a photo or video post which require different permissions and sending requests to different edges.

<!DOCTYPE html>
<html>
<head><title>My Feed </title></head>

<body>

<h1>Get My Feed and My Messages</h1>

<?php

require_once __DIR__ . '/vendor/autoload.php'; 

$fb = new \Facebook\Facebook([
  'app_id' => '{your-app-id}',           //Replace {your-app-id} with your app ID
  'app_secret' => '{your-app-secret}',   //Replace {your-app-secret} with your app secret
  'graph_api_version' => 'v5.0',
]);

try {
  // Get the \Facebook\GraphNodes\GraphEdge object for the current user.
  $feed_response = $fb->get('/me/feed', '{access-token}');
  $message_response = $fb->get('/me/feed?fields=message', '{access-token}');
  
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}


//Returns all data for feed 

$my_feed = $feed_response->getGraphEdge();

echo nl2br("All the feed data returned from the server: \r\n");
echo nl2br("\r\n");
echo nl2br($my_feed . "\r\n");

echo nl2br("\r\n");
echo nl2br("\r\n");

//Returns messages and message IDs

$my_feed_messages = $message_response->getGraphEdge();

echo nl2br("All the messages and message IDs returned from the server: \r\n");
echo nl2br("\r\n");

foreach ($my_feed_messages as $key => $value){
  foreach ($value as $key1 => $value2){
    echo nl2br($value2 . "\r\n");
  }
  echo nl2br("\r\n");
}

?>

</body>
</html>

Get a User Access Token

In this example you will get a User access token using the JavaScript SDK. This example consists of two files, index.php to intitialize the JavaScript SDK and get the access token, and token.php, where we use the token.

If you are not logged into Facebook in another window or browser tab, a popup will appear for you to login when you click the link. If you are logged into Facebook, when you click on the link a User access token will be printed.

Sample index.php File

<!DOCTYPE html>
<html>
<head><title>Get User Access Token</title></head>

<body>

  <h1>Get a Access Token using JavaScript SDK</h1>

 <p><a href="#" onClick="logInWithFacebook()">Log In with the JavaScript SDK</a></p>


  <script>

  <!-- Log User in -->

  logInWithFacebook = function() {
    FB.login(function(response) {
      if (response.authResponse) {
        alert('You are logged in & cookie set!');
        // Redirect the user to token.php file to use the token
        window.location.href = "https://your-url.com/token.php";
      } else {
        alert('User canceled login or did not fully authorize.');
      }
    });
    return false;
  };

  <!-- Initialize JS SDK to use JS helper to get access token -->

  window.fbAsyncInit = function() {
    FB.init({
      appId: '{your-app-id}',
      cookie: true, // This is important, it's not enabled by default
      version: 'v5.0'
    });
  };

  (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  <!-- Get user access token -->

FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    var accessToken = response.authResponse.accessToken;
  }
} );


</script>

</body>
</html>

Sample token.php File

<?php

// Get PHP SDK

require_once __DIR__ . '/vendor/autoload.php';

$fb = new \Facebook\Facebook([
  'app_id' => '{your-app-id}',
  'app_secret' => '{your-app-secrect}',
  'default_graph_version' => 'v5.0',
]);

// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.

require_once __DIR__ . '/index.php';

$helper = $fb->getJavaScriptHelper();

//

try {
  // Get the UserNode object for the current user name.
  $accessToken = $helper->getAccessToken();
  //$user_name_response = $fb->get('/me', $access_token);


} catch(\Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  echo 'nope, no token.';
  exit;
}


  echo '<h3>Access Token</h3>';
  //var_dump($accessToken->getValue());

  $access_token = $accessToken->getValue();
  echo nl2br("My token is ". $access_token);


  $_SESSION['fb_access_token'] = (string) $accessToken;

//Returns all data for feed


try {
   
// Get your UserNode object, replace {access-token} with your token
  $response = $fb->get('/me', '{access-token}');

} catch(\Facebook\Exceptions\FacebookResponseException $e) {
        // Returns Graph API errors when they occur
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
        // Returns SDK errors when validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$me = $response->getGraphUser();

       //Print out my name
echo nl2br("My name is " . $me->getName());


?>

</body>
</html>