#native_company# #native_desc#
#native_cta#

Talking to Facebook’s Social Graph with PHP

By W.J. Gilmore
on April 9, 2012

For better or worse, Facebook has grown to such a size that it has essentially become “an Internet within the Internet”. Sporting a community of more than 800 million users, more than 50% of whom log on every day, Facebook’s reach into the world’s personal, political and business spheres seems to know no boundaries. In recent years, it’s influence has dramatically grown thanks to the Facebook Platform, a set of APIs which third-parties can use to create or extend applications which tightly integrate with Facebook.com’s features and users.

Since the platform’s first release in May, 2007, more than one million developers from around the world have signed on to the Facebook Platform developer program. These days you’ll find traces of the platform on almost every major website (the ubiquitous Like button), saving users the hassle of remembering countless passwords thanks to Facebook Connect, and connecting gamers via some of the world’s most popular so-called “casual” games like Farmville and Mafia Wars.

At the center of Facebook and its platform is the social graph, which is an embodiment of the relationships Facebook users have with each other and with the many objects they interact with via the Facebook website and platform applications. As a Facebook Platform developer, you can use the APIs to bend Facebook’s social graph in ways which are limited only by your imagination, accessing and interacting with friends, events, pages, photos, notes, groups, and essentially anything else a Facebook user interacts with on a regular basis. PHP-minded developers are particularly fortunate, as the Facebook PHP SDK doesn’t only provide users a powerful solution for interacting with the social graph, but because it’s actively maintained by the Facebook development team is often the first of several available APIs to offer the latest features and bug fixes.

Installing the Facebook PHP SDK

The Facebook PHP SDK is most easily installed via its GitHub repository, meaning you can obtain the latest version simply by cloning the repository using your favorite Git client:

$ git clone https://github.com/facebook/php-sdk.git

Once installed, add the repository’s src directory to the PHP include_path. In most cases you’ll need to restart your Web server in order for changes to your php.ini file to take effect.

Obtaining a Facebook API Key

In order to interact with the Graph API you’ll need to register your application on the Facebook Developers website. This only takes a moment to do, and once finished you’ll be provided with a pair of application credentials (an API key and secret key). Be sure to write down your credentials as we’ll be using them in the examples to follow.

Retrieving Public Profile Information

Perhaps the easiest Graph API-related example involves retrieving a user’s public profile information. Of course, the level of information detail returned will vary according to the user’s privacy settings. At a minimum, you should expect to retrieve a user’s name, gender and locale (this has at least been my experience interacting with my own profile which exposes the minimum level of information). Execute the following code to retrieve my public profile data:

Execute this code and the browser will output the following data:

Array ( 
  [id] => 501632489 
  [name] => Jason Gilmore 
  [first_name] => Jason 
  [last_name] => Gilmore 
  [username] => wjgilmore 
  [gender] => male 
  [locale] => en_US 
)

Obtaining Information About the Currently Logged-In User

Of course, it’s unlikely you’re going to want to repeatedly retrieve information about a certain static user. Instead, you’ll want to dynamically obtain information about the user currently visiting your website or application. To do so the user will need to provide express permission for your application to interact with his Facebook account. This is done by redirecting the user to Facebook by way of a special URL, at which point the user will be prompted to login to your application (see Figure 1).

Facebook Social Graph - PHP - Figure 1
Figure 1. Logging into a Facebook Application

Once the user presses the Log In button, he will be redirected to your application, at which point you will be able to obtain useful Facebook profile details. Before writing any code though you’ll first need to configure your application’s website URL, as Facebook will use this URL as the redirection endpoint after authenticating the user. Return to your application’s page over on the Facebook Developer website and look for the section presented in Figure 2:

Facebook Social Graph - PHP - Figure 2
Figure 2. Identifying the Facebook Application Redirection URL

Keep in mind that you need to identify the specific redirection URL, such as http://www.wjgilmore.com/phptips/welcome.php, rather than simply the URL domain. Once defined, add the following code to the script associated with that URL:

<?php 

  require_once 'facebook.php';

  $facebook = new Facebook(array(
    'appId'  => 'My-APP-ID',
    'secret' => 'My-SECRET-KEY',
  ));

  $user = $facebook->getUser();

  if ($user) {
    try {
      $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
      error_log($e);
      $user = null;
    }
  }

  if ($user) {
    $logoutUrl = $facebook->getLogoutUrl();
  } else {
    $loginUrl = $facebook->getLoginUrl();
  }

?>

<?php if ($user) { ?>


  <a href="<?php echo $logoutUrl; ?>" target="_blank">Logout</a>

<?php } else { ?>


  <a href="<?php echo $loginUrl; ?>" target="_blank">Login with Facebook</a>

<?php } ?>


<?php if ($user) { ?>

Execute this code and after clicking the Login with Facebook link and confirming that you’d like to login to your own application, you should be presented with a variety of information associated with your public profile. For instance, the information returned from my public profile follows:

Array
(
  [id] => 501632489
  [name] => Jason Gilmore
  [first_name] => Jason
  [last_name] => Gilmore
  [link] => http://www.facebook.com/wjgilmore
  [username] => wjgilmore
  [hometown] => Array
    (
        [id] => 112449512101262
        [name] => Hubbard, Ohio
    )

  [location] => Array
    (
        [id] => 108450559178997
        [name] => Columbus, Ohio
    )

  [gender] => male
  [timezone] => -5
  [locale] => en_US
  [languages] => Array
    (
      [0] => Array
        (
            [id] => 113153272032690
            [name] => Italian
        )

    )

  [verified] => 1
  [updated_time] => 2011-11-08T18:38:33+0000
)

After logging in to your application for the first time (and thereby granting permission to access basic profile information), the user will not be repeatedly asked to grant access anew; instead they will only be prompted to login anew if the API is unable to determine a current Facebook session.

Because the user’s profile ID is returned (in my case it is 501632489), you can save this ID in your local database, and then compare it to any arriving Facebook user who has granted permission for your application to access his profile information. This ID provides a convenient and easy conduit for retrieving and updating local profile information!

Where to From Here?

The code and concepts covered in this introductory article really only scratch the surface in terms of what you can do with the Graph API. Be sure to consult the Graph API documentation for additional insight into the possibilities!

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.