Facebook PHP API Applications: A Second Look

This is the second part of the Facebook PHP API tutorial. The first part ran on August 11. It covered the most basic features, such as adding the basic Facebook “Like” button, the “Recommendations” plugin and registering your applications in Facebook to get an Application ID and Secret key. In this part, we’ll delve deeper.

Specifically, we’ll go into the details of basic PHP scripting for communicating with the API. After reading this tutorial, you can be confident of how to establish basic communication with the Facebook API, retrieve basic user information and then display that information on your website.

The Raw PHP Facebook Developer Documentation Code

For reference, all basic and initial source code samples were obtained from the Facebook developer page. This code, however, is not completely ready to be implemented and requires some changes before it can be considered fully working.

This tutorial will dig into details and attempt to achieve the following simple objectives:

1. Create a PHP application web page hosted on another website (not on Facebook).

2. Allow a Facebook user to log in from your website via that web page.

3. Enable the PHP web application to connect to Facebook using the API application keys.

4. Allow Facebook to confirm the application and retrieve user profile information, which it will provide to the requesting website.

5. Enable the web application to then display the retrieved information on the page.

The flow chart will look like this:

{mospagebreak title=Understanding the Facebook Graph API}

As a Facebook developer, it is important that you understand the Facebook Graph. Facebook also call this the "social graph."

Say, for example, you want to retrieve the following data from a Facebook user’s profile:

  • User ID
  • Name
  • Gender
  • Facebook URL link

Facebook uses JSON objects when presenting user profile data. A user’s profile can be obtained via their Facebook graph’s sub-domain

According to Facebook, every object in the social graph contains a unique ID. So all Facebook users have a unique ID assigned to them.

Another thing you need to know is that you can access a Facebook user’s information via the graph URL; you just need to append the Facebook user’s ID. For example:

https://graph.facebook.com/ID

where "ID" is the actual user ID. The data are presented as JSON objects. For example, if your user ID is 747166266, you can access it in the address bar as follows:

https://graph.facebook.com/747166266

See the screen shot below:

The required get_facebook_cookie_function

This is the start of the PHP script discussion. We’re going to analyze the sample script provided by the Facebook API. The first step is to get the Facebook cookie. This is will be used by the succeeding scripts to check whether or not the user has logged in to your website using their Facebook account.

To do this in your PHP web application, paste the following code at the top of your PHP scripts (the very first line of code):

<?php
define(‘FACEBOOK_APP_ID’, ‘***YOUR FACEBOOK APPLICATION ID HERE***’);
define(‘FACEBOOK_SECRET’, ‘***YOUR FACEBOOK SECRET APPS KEY HERE***’);
function get_facebook_cookie($app_id, $application_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], ‘"’), $args);
  ksort($args);
  $payload = ”;
  foreach ($args as $key => $value) {
    if ($key != ‘sig’) {
      $payload .= $key . ‘=’ . $value;
    }
  }
  if (md5($payload . $application_secret) != $args['sig']) {
    return null;
  }
  return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>

You need a Facebook Application ID and secret apps key, to be placed under "Define."

{mospagebreak title=Is the user logged in?}

Now that you have a fully working PHP function to get cookies, let’s find out whether or not the user is logged in. If the user is not logged in, the code should present the Facebook login button; otherwise, it should retrieve user data from Facebook social graph (https://graph.facebook.com/) for the corresponding user ID.

<?php if ($cookie) {
//cookie is set, user is logged in
$user = json_decode(file_get_contents(‘https://graph.facebook.com/’.$cookie['uid']));
//Display the facebook user ID, name, gender and Facebook URL in the web browser
echo ‘<br />';
echo ‘Your Facebook ID: ‘.$user->{‘id’};
echo ‘<br />';
echo ‘Your name: ‘.$user->{‘name’};
echo ‘<br />';
echo ‘Your gender: ‘.$user->{‘gender’};
echo ‘<br />';
echo ‘Your Facebook URL: ‘.$user->{‘link’};
echo ‘<br />';
echo ‘<fb:login-button autologoutlink="true"></fb:login-button>';
}
else
{
//user is not logged in, display the Facebook login button
echo ‘<h2>Facebook Application Test page</h2>';
echo ‘<br />';
echo ‘This is the most basic Facebook application PHP source code that will grab the user Facebook full name, gender and Facebook URL.';
echo ‘<br />Then displays those information in the web browser once the user has successfully logged in';
echo ‘<br /><br />';
echo ‘<fb:login-button autologoutlink="true"></fb:login-button>';
}
?>

Code Discussion

The PHP condition that checks to see if the cookie is set, is this: if ($cookie)

Basically the cookie value is defined by the previous get_facebook_cookie function: $cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);

If the user is logged in, the profile information can be retrieved from Facebook using this function:

$user = json_decode(file_get_contents(‘https://graph.facebook.com/’.$cookie['uid']));

 Since the data are JSON objects, it is decoded using the php function json_decode in order for it to be properly displayed on the browser.

To get the profile information from the decoded JSON objects, set up your echo command this way:

echo ‘Your Facebook ID: ‘.$user->{‘id’};
echo ‘<br />';
echo ‘Your name: ‘.$user->{‘name’};
echo ‘<br />';
echo ‘Your gender: ‘.$user->{‘gender’};
echo ‘<br />';
echo ‘Your Facebook URL: ‘.$user->{‘link’};

$user->{‘id’} contains the decoded user ID, while user->{‘name’} contains the decoded Facebook user name, etc.

The Facebook login button is this:

 echo ‘<fb:login-button autologoutlink="true"></fb:login-button>';

This will display "Login" if the user is not yet logged in and "LoggedOut" if the user is logged in to Facebook.

This is the screen shot of the PHP application when the user is not logged in.

When the user clicks the login button, a pop-up window will then show, and the user will enter their email and password as the required information for logging in.

After logging in, once the application retrieves the user information from Facebook’s social graph, it will look like the screen shot below:

The required JavaScript SDK at the bottom of Facebook PHP apps

Javascript SDK is a client side script responsible for providing functionality for authentication and sharing. You can read more information about the Facebook JavaScript SDK at the link. 

This code is required; it is placed at the bottom of your Facebook PHP web application:

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: ‘<?= FACEBOOK_APP_ID ?>’, status: true,
cookie: true, xfbml: true});
FB.Event.subscribe(‘auth.login’, function(response) {
window.location.reload();
});
</script>
</body>
</html>

{mospagebreak title=Final Facebook PHP API Script – Display basic user information}

Below is the final, working PHP script that will communicate to the Facebook API and retrieve very basic user information. You can also download the script at the link. 

<?php
define(‘FACEBOOK_APP_ID’, ‘***YOUR FACEBOOK APPLICATION ID HERE***’);
define(‘FACEBOOK_SECRET’, ‘***YOUR FACEBOOK SECRET APPS KEY HERE***’);
function get_facebook_cookie($app_id, $application_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], ‘"’), $args);
  ksort($args);
  $payload = ”;
  foreach ($args as $key => $value) {
    if ($key != ‘sig’) {
      $payload .= $key . ‘=’ . $value;
    }
  }
  if (md5($payload . $application_secret) != $args['sig']) {
    return null;
  }
  return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($cookie) {
//cookie is set, user is logged in
$user = json_decode(file_get_contents(‘https://graph.facebook.com/’.$cookie['uid']));
//Display the facebook user ID, name, gender and Facebook URL in the web browser
echo ‘<br />';
echo ‘Your Facebook ID: ‘.$user->{‘id’};
echo ‘<br />';
echo ‘Your name: ‘.$user->{‘name’};
echo ‘<br />';
echo ‘Your gender: ‘.$user->{‘gender’};
echo ‘<br />';
echo ‘Your Facebook URL: ‘.$user->{‘link’};
echo ‘<br />';
echo ‘<fb:login-button autologoutlink="true"></fb:login-button>';
}
else
{
//user is not logged in, display the Facebook login button
echo ‘<h2>Facebook Application Test page</h2>';
echo ‘<br />';
echo ‘This is the most basic Facebook application PHP source code that will grab the user Facebook full name, gender and Facebook URL.';
echo ‘<br />Then displays those information in the web browser once the user has successfully logged in';
echo ‘<br /><br />';
echo ‘<fb:login-button autologoutlink="true"></fb:login-button>';
}
?>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: ‘<?= FACEBOOK_APP_ID ?>’, status: true,
cookie: true, xfbml: true});
FB.Event.subscribe(‘auth.login’, function(response) {
window.location.reload();
});
</script>
</body>
</html>

How to implement the script on your website

First, make sure your website and your account complies with the basic requirements outlined in the first part of this tutorial. 

Second, you need to get your own application ID and apps secret key, which you need to define in the above source code.

Third, you need to save your PHP application (for example, my_facebook_api.php)

Fourth, upload the script into your website server. For testing purposes, start testing it  at the server root directory. For example: http://www.php-developer.org/my_facebook_api.php

Fifth, launch the application URL (http://www.php-developer.org/my_facebook_api.php) in the browser. Try logging in first by using your own Facebook account to see if it provides any errors.

This is just a very basic implementation to show how the Facebook API works using PHP. In the upcoming Facebook API tutorials, you will learn how to grab detailed user information, such as friends, photos, and so forth. Details for creating your own Facebook apps, which can be hosted on your website and can be used by other Facebook users, will also be covered. 

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort