Building a Facebook Application: Part 1

Exclusive offer: get 50% off this eBook here
Learning Facebook Application Development

Learning Facebook Application Development — Save 50%

A step-by-step tutorial for creating custom Facebook applications using the Facebook platform and PHP

$23.99    $12.00
by Dr Mark Alexander Bain Hasin Hayder | July 2009 | PHP

You'll obviously want to start building applications, and that's just what we'll do in this two-part article. By the end of this two-part article by Dr. Mark Alexander Bain and Hasin Hayder, you'll be able to:

  • Extract Facebook information to be displayed by your application.
  • Store information in the Facebook cache, so that it can be displayed on your users' profile pages.
  • Store your own custom data.

The first part will cover the concepts of developing a simple Facebook application and also the way to write the Facebook profile.

A simple Facebook application

Well, with the Facebook side of things set up, it's now over to your server to build the application itself. The server could of course be:

  • Your web host's server – This must support PHP, and it may be worthwhile for you to check if you have any bandwidth limits.
  • Your own server – Obviously, you'll need Apache and PHP (and you'll also need a fixed IP address).

Getting the server ready for action

Once you have selected your server, you'll need to create a directory in which you'll build your application, for example:

mkdir -p /www/htdocs/f8/penguin_pi
cd /www/htdocs/f8/penguin_pi

If you haven't already done so, then this is the time to download and uncompress the Facebook Platform libraries:

wget http://developers.facebook.com/clientlibs
/facebook-platform.tar.gz
tar -xvzf facebook-platform.tar.gz

We're not actually going to use all of the files in the library, so you can copy the ones that you're going to use into your application directory:

cp facebook-platform/client/facebook.php
cp facebook-platform/client/facebookapi_
php5_restlib.php

And once that's done, you can delete the unwanted files:

rm -rf facebook-platform.tar.gz facebook-platform

Now, you're ready to start building your application.

Creating your first Facebook application

Well, you're nearly ready to start building your application. First, you'll need to create a file (let's call it appinclude.php) that initiates the application.

The application initiation code

We've got some code that needs to be executed every time our application is accessed, and that code is:

<?php
require_once 'facebook.php'; #Load the Facebook API
$appapikey = '322d68147c78d2621079317b778cfe10';
#Your API Key
$appsecret = '0a53919566eeb272d7b96a76369ed90c';
#Your Secret
$facebook = new Facebook($appapikey, $appsecret);
#A Facebook object
$user = $facebook->require_login(); #get the current user
$appcallbackurl = 'http://213.123.183.16/f8/penguin_pi/';
#callback Url
#Catch an invalid session_key
try {
if (!$facebook->api_client->users_isAppAdded()) {
$facebook->redirect($facebook->get_add_url());
}
} catch (Exception $ex) {
#If invalid then redirect to a login prompt
$facebook->set_user(null, null);
$facebook->redirect($appcallbackurl);
}
?>

You'll notice that the code must include your API Key and your secret (they were created when you set up your application in Facebook). The PHP file also handles any invalid sessions.

Now, you're ready to start building your application, and your code must be written into a file named index.php.

The application code

Our application code needs to call the initiation file, and then we can do whatever we want:

<?php
require_once 'appinclude.php'; #Your application
initiation file
echo "<p>Hi $user, ";
echo "welcome to Pygoscelis P. Ellsworthy's
Suspect Tracker</p>";
?>

Of course, now that you've written the code for the application, you'll want to see what it looks like.

Viewing the new application

Start by typing your Canvas Page URL into a browser (you'll need to type in your own, but in the case of Pygoscelis P. Ellesworthy's Suspect Tracker, this would be http://apps.facebook.com/penguin_pi/):

Building a Facebook Application: Part 1

You can then add the application just as you would add any other application:

Building a Facebook Application: Part 1

And at last, you can view your new application:

Building a Facebook Application: Part 1

It is worth noting, however, that you won't yet be able to view your application on your profile. For the time being, you can only access the application by typing in your Canvas Page URL. That being said, your profile will register the fact that you've added your application:

Building a Facebook Application: Part 1

That's the obligatory "Hello World" done. Let's look at how to further develop the application.

Learning Facebook Application Development A step-by-step tutorial for creating custom Facebook applications using the Facebook platform and PHP
Published: May 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Developing the simple application

Admittedly, that's not the most exciting application in the world, and certainly not one that's going to get you hundreds of users. However, it is enough for you to see the basics of a Facebook application. We can now look at advancing the application further.

So, let's see how to put some of the code into an application that we can actually use. You'll need to edit index.php again, and just as before, start by calling the application initiation file:

<?php
require_once 'appinclude.php';

Next, we can introduce some FBML to create a personal welcome message:

echo "
<p>Hi <fb:name useyou=false uid=$user
firstnameonly=true></fb:name>,
welcome to Pygoscelis P. Ellsworthy's Suspect
Tracker</p>
";
?>

And mix in some HTML to format the output:

<h4>The Usual Suspects</h4>
<table cellpadding=0 cellspacing=0>
<tr><td>

Then, we can use FBML to output the user's picture and name:

<?php
echo "<fb:profile-pic uid=$user></fb:profile-pic>";
?>
</td></tr>
<tr><td>
<?php
echo "<fb:name useyou=false uid=$user
firstnameonly=false></fb:name>";
?>
</td></tr></table>

The end result is that we've used <fb:profile-pic> and <fb:name> as well as HTML and PHP to produce a recognizable Facebook application:

Building a Facebook Application: Part 1

Our application uses the $user variable that we obtain in appinclude.php:

$user = $facebook->require_login()
 

You'll realize, of course, that we're making use of the API in order to do this. So let's make further use of the API by obtaining the list of our user's friends and displaying their details in our application. Here, we're going to make use of $facebook->api_client->friends_get and $facebook->api_client->users_getInfo. However, we're not going to do all of our coding in index.php, instead we're going to add a function into appinclude.php. So, the first step is to define the function at the end of the file:

function simple_facebook_app () {
//Define any required global variables
global $facebook, $user, $friends, $profile_field_array;
//Display a welcome message
$text = <<<EndOfText
<p>Hi <fb:name useyou=false uid=$user
firstnameonly=true></fb:name>,
welcome to Pygoscelis P. Ellsworthy's Suspect
Tracker</p>
<h4>The Usual Suspects</h4>
<table cellpadding=0 cellspacing=0><tr>
EndOfText;
//Obtain a list of our user's friends
$friends =
$facebook->api_client->friends_get();
//and then get an array containing the friends' details
$friend_details =
$facebook->api_client->users_getInfo($friends,
$profile_field_array);
$c = 1;
//Loop through each of the user's friends' details
foreach ($friend_details as $friend) {
//Now use HTML and a counter to limit the display to 3 columns
if ($c > 3) {
$c=1;
$text .= "</tr>n<tr>";
}
$text .= "<td><table><tr><td>";
//Display the friend's picture, name and city
$friend_uid = $friend['uid'];
$friend_first_name = $friend['first_name'];
$friend_last_name = $friend['last_name'];
$text .= <<<EndOfText
<fb:profile-pic uid=$friend_uid></fb:profile-pic>
</td></tr>n<tr><td>
<a href=http://www.facebook.com/profile.php?id=$friend_uid>
$friend_first_name $friend_last_name</a></td></tr>n
<tr><td>Location:
EndOfText;
$city = $friend['hometown_location']['city'];
if ($city == "") {$text .= "Unknown";}
else {$text .= $city;}
$text .= "</td></tr></table></td>";
//Update the counter recording the number of columns
$c++;
}
$text .= "</tr>n</table>";
//And finally output the result to the screen
echo $text;
}

Our index.php file now becomes very simple:

<?php
require_once 'appinclude.php';
simple_facebook_app () ;
?>

If you reload the application, you'll see all the user's (that is your) friends' details displayed on the screen:

Building a Facebook Application: Part 1

Examining variables

While writing the code, there may have been a few times you've wondered about the variables that we're using. For example, what is $profile_field_array? Well, the print_r method can help us:

print_r ($profile_field_array);

And we can now see exactly what's contained in the array:

Building a Facebook Application: Part 1

We can do the same with the $friend_details array, by creating a new function in appinclude.php:

function get_friends_details ($field_array) {
global $facebook;
$friends = $facebook->api_client->friends_get();
return $facebook->api_client->users_getInfo($friends,
$field_array);
}

and then calling it from index.php:

print_r (get_friends_details ($profile_field_array));

When you reload your application, you're able to see exactly what's being passed from Facebook to your application:

Building a Facebook Application: Part 1

As you can see, quite a lot of information is being passed back (much of which we don't need). Fortunately, we can ask Facebook for only those fields that we actually require:

$field_array = array('uid','first_name',
'last_name','hometown_location');
print_r (get_friends_details ($field_array));

The end result is that less data is passed back to your application (which therefore gives a faster response time):

Building a Facebook Application: Part 1

Of course, we can improve things even more by making use of FQL.

Using FQL in your application

If you look back at the code that we've just written, then you'll see that we accessed Facebook twice to obtain data. Once for the list of friends, and then for the friends' details. One of the advantages of using FSQL is that we can extract the data in a single transaction by making use of the $facebook->api_client->fql_query method:

global $facebook, $user;
$sql = <<<EndSQL
SELECT first_name, last_name,
hometown_location
FROM user
WHERE uid IN (SELECT uid1
FROM friend
WHERE uid2=$user)
EndSQL;
$friend_details = $facebook->api_client->
fql_query($sql);

The end result is that we still load $friend_details with an array containing the information about our user's friends, but we've made only one call to the database instead of two.

A second advantage is that we can start filtering the information (again speeding up the application). For example we can change the application to show only the friends who are in England:

$sql = <<<EndSQL
SELECT first_name, last_name,
hometown_location
FROM user
WHERE uid IN (SELECT uid1
FROM friend
WHERE uid2=$user)
AND hometown_location.country = 'England'
EndSQL;
$friend_details = $facebook->api_client->
fql_query($sql);

If this FQL is used in our application, then we'll still see three columns of friends, but they'll only be those in England:

Building a Facebook Application: Part 1

Of course, if you want to be really clever, you could convert the above code into a function, which when supplied with a country returns an array of friend IDs. However, I'll leave that to you. Instead, we'll turn our attention to the Facebook profile.

Here's a question: how many Facebook applications display something on the user's profile page? Well, at the moment, all of them, except yours. Let's rectify that now.

Writing to the Facebook profile

So far we've only been working with the application page; this means that you need to either access the application via the left-nav panel, or by typing the Canvas Page URL into your browser (e.g. http://apps.facebook.com/penguin_pi/). However, if you go to your profile page, you'll see:

Nothing.

And yet this is where your users will want to see your application, so that's a bit of a problem. Well, not really.

However, you may remember that Facebook keeps a cache, and it's this cache that's used to display information on a profile page. All we have to do is write to the cache.

Updating the Facebook Cache

So, we need to find a way to write the output to the profile, and we do this by making use of the API, and in particular, the $facebook->api_client->profile_setFBML method:

$fbml_text = <<<EndOfText
<p>Hi <fb:name useyou=false uid=$user
firstnameonly=true></fb:name>,
welcome to Pygoscelis P. Ellsworthy's
Suspect Tracker</p>
<fb:user-table cols="3">
<fb:user-item uid=$user />
</fb:user-table>
EndOfText;
$facebook->api_client->profile_setFBML
($fbml_text, $user);
print "Text written to Facebook Profile";

You'll notice that we need to write all of the FMBL to a variable ($fbml_text), and that we then use $facebook->api_client->profile_setFBML to produce an output for the profile.

You may also be wondering about the last line of code: why do we need to output text as well as the FBML? The reason is quite simple. If we run the application directly (by entering the Canvas Page URL) we'll get an error if there is no output at all. So our application needs to send the FBML to the Cache for the profile and produce an output for the application.

So, all you have to do now is type your Canvas Page URL into your browser:

Building a Facebook Application: Part 1

And then go to your profile page to see the end result:

Building a Facebook Application: Part 1

At this point, you're probably wondering if there's an easier way to refresh the FBML. After all, having to enter the Canvas Page URL, and then looking at the profile page to see the effect of your changes does take time. And of course, there is an easy answer. Just change the line:

print "Text written to Facebook Profile";

to:

$facebook->redirect($facebook->get_facebook_url() . 
'/profile.php');

How does this help? The line of code simply redirects the application back to the profile page. This means that instead of carrying out two steps (going to the Canvas Page URL and then back to the profile page), you can now just click on the link to your application in the left-hand navigation panel:

Building a Facebook Application: Part 1

Once you click on your link (and the page has refreshed), you can just scroll down to your application and see the effect of your changes.

And while we're on it, we can also change the code to incorporate some of the work that we discussed earlier in the article. I had mentioned earlier that you can write a function to extract a user's friend's details by country, here it is:

function get_friends_details_by_country ($country) {
global $facebook, $user;
$sql = <<<EndSQL
SELECT uid, first_name, last_name, hometown_location
FROM user
WHERE uid IN (SELECT uid1
FROM friend
WHERE uid2=$user)
AND hometown_location.country = '$country'
EndSQL;
return $facebook->api_client->fql_query($sql);
}

Next, we can create another couple of functions that will write to the cache:

function tabulate_friends ($friend_details, $cols) {
/*Tabulating a list of friends is quite useful,
and so we'll put in its own function.
That way we can easily use it elsewhere*/
$tabulate_friends = "<fb:user-table cols=$cols>";
foreach ($friend_details as $friend) {
$tabulate_friends .= "<fb:user-item uid=" .
$friend['uid'] . " />";
}
$tabulate_friends .= "</fb:user-table>";
return $tabulate_friends;
}
function display_friends_by_country ($country) {
/*This simple function sends a subtitle
and table of friends to the profile */
global $facebook,$user;
$fbml_text = <<<EndOfText
<fb:subtitle>
<fb:name useyou=false uid=$user firstnameonly=true
possessive=true></fb:name>
Suspect List
</fb:subtitle>
EndOfText;
$friend_details = get_friends_details_by_country('England');
$fbml_text .= tabulate_friends ($friend_details, 4);
$facebook->api_client->profile_setFBML($fbml_text, $user);
$facebook->redirect($facebook->get_facebook_url() . '/profile.php');
}

And then, it's just a matter of updating index.php to use this new functionality:

<?php
require_once 'appinclude.php';
display_friends_by_country('England');
?>

Once you've saved index.php again, and clicked on the link to your application you'll see something like the following:

Building a Facebook Application: Part 1

Now, that's all fine, but it's a bit static isn't it? You (and any of your friends) can see the information that was sent to the FBML cache.

Summary

This article has been all about creating your first application. We've also seen how to add it into Facebook.  In the next part, we'll look at how to start making your application a bit more dynamic.

Learning Facebook Application Development A step-by-step tutorial for creating custom Facebook applications using the Facebook platform and PHP
Published: May 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Dr Mark Alexander Bain

Dr. Mark Alexander Bain first started customizing CRM systems back in the mid '90s when he was team leader for Vodafone's Cascade project – the team took the 'out-of-the-box' Clarify CRM and turned it into a radio base station planning application, complete with a workflow engine for passing jobs between the different departments involved in the planning, building, and implementation of a radio network. Since then he's lectured at the University of Central Lancashire, and currently Mark writes articles on all things Linux and Open Source for Linux Format, Newsforge.com and Linux Journal. SugarCRM customization, therefore, seems the obvious choice for this, his second book, since it combines Mark's knowledge of working with commercial CRMs and the Open Source philosophy. Mark works from his home on the edge of the Lake District in the UK, where he lives with his wife, two dogs and two cats, and gets the odd visit from his sons – Michael and Simon.

Hasin Hayder

Hasin Hayder graduated in Civil Engineering from the Rajshahi University of Engineering and Technology (RUET) in Bangladesh. He is a Zend-certified Engineer and expert in developing localized applications. He is currently working as a Technical Director in Trippert Labs and managing the local branch in Bangladesh. Beside his full time job, Hasin writes his blog at http://hasin.wordpress.com, writes article in different websites and maintains his open source framework Orchid at http://orchid.phpxperts.net. Hasin lives in Bangladesh with his wife Ayesha and his son, Afif.

Books From Packt

Drools JBoss Rules 5.0 Developer's Guide
Drools JBoss Rules 5.0 Developer's Guide

Plone 3 Theming
Plone 3 Theming

WordPress 2.7 Cookbook
WordPress 2.7 Cookbook

Building Enterprise Ready Telephony Systems with sipXecs 4.0
Building Enterprise Ready Telephony Systems with sipXecs 4.0

PHP and script.aculo.us Web 2.0 Application Interfaces
PHP and script.aculo.us Web 2.0 Application Interfaces

Expert Cube Development with Microsoft SQL Server 2008 Analysis Services
Expert Cube Development with Microsoft SQL Server 2008 Analysis Services

WordPress 2.7 Complete
    WordPress 2.7 Complete

Drupal 5 Views Recipes
Drupal 5 Views Recipes

 

 

No votes yet
IrretenoG by
You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material
sakdreasy by
Very Interesting Blog! Thank You For Thi Blog!
I find myself coming to your by
I find myself coming to your blog more and more often to the point where my visits are almost daily now!
Great Info by
You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material
Great Post by
I find myself coming to your blog more and more often to the point where my visits are almost daily now!
Great Post by
Very Interesting Information! Thank You For Thi Blog!

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
G
u
7
n
1
N
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software