There’s been a fair bit of interest in Facebook as an applications platform, judging from declarations that it’s the new Visual Basic or the next Windows and the number of developers signing up for the Facebook Developer Garage taking place here in Toronto on August 7th. I recently started trying out development for Facebook and will share my notes, experiences and findings here from time to time.
This article will cover the basics of writing a simple Facebook application using PHP 5 — by the end, you should be able to write a simple, if not terribly useful, Facebook application. Most of this article will deal with the initial setup required.
What You’ll NeedYou’ll need:
* A Facebook account
* A server running PHP 5 that can be accessed from the outside world via URLs
* Facebook’s PHP client library code, which you can download from the Facebook Developers Resources page.
Just a Little BackgroundFacebook applications don’t live on Facebook’s server. Instead, they live on their developers’ servers and are called by Facebook whenever a user enters them. Facebook uses a callback metaphor to describe this relationship, because it’s similar to passing a reference or a pointer for a callback function to another function.
Here’s how Facebook applies the callback metaphor with third-party applications:

This arrangement lets you use whatever server configuration you prefer, including keeping your own database so that your applications can store their own data in addition to querying Facebook’s data.
developers.facebook.com vs. facebook.com/developersThese two sites serve completely different purposes:
*
developers.facebook.com is for news, documentation, resources and tools. It’s the official home of all Facebook development reference material, and you don’t need a Facebook account to access this site.
*
facebook.com/developers could be considered a “control panel” for developers. It looks a lot like a page for a Facebook group — there’s a “latest news” panel, a discussion board and a list of members — and it’s where you manage the applications that you are creating. You need a Facebook account to access this site, and you need to access this site to create Facebook applications.
Let’s Set Up an App!Since we want to build an application, let’s go to facebook.com/developers. If you’re already logged into Facebook, you’ll arrive at the page immediately. If you’re not logged in, you’ll be asked to log in first.
The screenshot below shows the facebook.com/developers page. Click on the “Set up new application” link, which is highlighted in red in the screenshot:

You’ll be taken to the “New Application” page, shown below:

Your first three steps are:
*
Enter the name of your application into the “Application Name” field. This will be the display name of your application. In my case, I named it “Joey’s Test Application”; feel free to give it any name you like.
*
Read the terms and conditions and check the checkbox to indicate that you have read and agree to the terms and conditions. If you haven’t read the terms and conditions yet, they’re here.
*
Click the “Optional Fields” link. This will reveal more fields, which are shown in the screenshot below:

Here’s how you should fill in these new fields:
*
Support E-mail: This will be automatically filled in with the email address that you use to log into Facebook. This is also an email address that will be made available to your users for support calls. You might want to change the address in this field to one that you created specifically for supporting your Facebook app. Since I log into Facebook with my work email address, I kept the default value.
*
Callback URL: Remember, the code for your Facebook app doesn’t live on Facebook’s server; it lives on your server. Fill this field with the URL for the directory in which your app will reside.
In my case, I’m using my server at nerdy-deeds.com, where I’ve created a directory for Facebook apps called
facebook, and within that directory, a directory for my test app called
test-app-01. So the URL for callback URL for my Facebook app is
http://nerdy-deeds.com/facebook/test-app-1.
*
Canvas Page URL: Within Facebook’s navigation system, your app will be accessible from some subdirectory of
apps.facebook.com. You need to provide a unique name for that directory. There’s a little Ajax-y magic attached to this field; there’s an indicator to the right of the field that updates as you type, letting you know if the directory name you’re providing is taken or not.
Note: The Facebook filename system allows only
letters, dashes and underscores. Numbers are not allowed. I discovered this after trying to use a name like “joeydevilla-01″ (I assumed I’d make a whole bunch of test apps before trying to build something a little more real, so a numbered naming system made sense). After finding out about this quirk, I entered
joeydevilla-a into the field.
*
Use FBML / Use iframe: FBML is short for “Facebook Markup Language” and provides all sorts of extra querying and formatting capabilities. Select “Use FBML”.
*
Application Type: Select “Website”.
*
IP Addresses of Servers Making Requests: Requests from IP addresses other than the ones listed in this field will be rejected. For this example, leave this blank.
*
Can your application be added on Facebook? We want to be able to add this app to our own account at the very least, so select “Yes”. Note that more options will appear in the area below the “Optional Fields” area.
*
TOS URL: This is an URL on your server where the “Terms of Service” page for your app lives. For this example, leave this blank.
When you clicked on “Yes” in response to
Can your application be added on Facebook?, a couple of new areas on the page appeared:
Installation Options and
Integration Points. Let’s look at filling in the
Installation Options part first:

*
Post-Add URL: This is the URL that the user is redirected to after installing your application. Enter your full Canvas Page URL. In my case, I entered
http://apps.facebook.com/joeydevilla-a.
*
Application Description: You can put a brief description of your app here for the benefit of users who are considering adding it. Since this is a test application, you can leave this blank if you like.
*
Post-Remove URL: This is the URL that the user is redirected to after removing your application. We’re not going to concern ourselves with this issue, so leave this blank.
*
Default FBML: This is the default content of the application if it hasn’t been set by your app. I decided to go with the standard greeting of “Chef” from the TV series
South Park:
Hello there, children!.
*
Default Profile Box Column: This specifies which column of the page your app should live in when first added by the user. Leave this at the default column,
Wide.
*
Developer Mode: This specifies whether only developers of the application are allowed to add this app. Since this is a test app for my own use only, I decided to check this box.
Now let’s look at the
Integration Points area:

*
Side Nav URL: This is the URL for the app if a link to it is to appear in the side navigation. Set this to the full canvas URL for your app. In my case, that’s
http://apps.facebook.com/joeydevilla-a.
*
Edit URL: This is an “Edit” link in your app’s profile box for users who’ve just added your app and are looking at their own profile. Leave this blank.
*
Privacy URL: This lets you specify a link for a privacy configuration page for your application. Leave this blank.
*
Help URL: This lets you specify a link for a help page for your application. Leave this blank.
*
Private Installation: Checking this box disables News Feed and Mini-Feed installation stories for your application. The first time I built a Facebook app, a number of friends started annoying me with “What are you building?” messages, so I’ve decided to check this when building test applications like this one.
*
Message Attachment: We’re not dealing with attachments in this application, so leave these fields blank.
That’s all the information we need — click the
Submit button at the bottom of the page.
Your Facebook Application’s API Key and SecretAfter you click the
Submit button on the
New Application page, you’ll be at the
My Applications page, shown below:

The
My Applications page lists your applications, some details about them and provides the option of editing or deleting any of your applications. We’ll need two pieces of information for the next step: the
API Key and
secret for your newly-registered app.
Let’s look at the library code.
The Library CodeOnce again, you can get the library code from the
Facebook Developer Resources page.
The library code, once expanded, is a directory named
facebook-platform that contains these subdirectories:
*
client: This contains the library code for PHP 5. We’ll be using the files within it for this example.
*
footprints: This contains a sample application that you can examine to see how to write Facebook apps. We won’t be using anything from it for this example.
*
php4client: This contains the library code for PHP 4. We won’t be using anything from it for this example.
The
client directory contains these three files:
*
facebook.php: Contains the definition of the Facebook class, which you use to access Facebook. We’ll be using it in this example.
*
facebook_desktop.php: Contains the definition of the FacebookDesktop, a subclass of Facebook with extra definitions for desktop applications. We won’t be using it in this example.
*
facebookapi_php5_restlib.php: Contains the definition of the FacebookRestClient class, which is contained within the Facebook class. This is the class with the really interesting methods — the ones that get all sorts of information from Facebook — and we’ll be using it in this example.
FTP the files
facebook.php and
facebookapi_php5_restlib.php to your server, into the directory corresponding to your Facebook callback URL. In my case, I would FTP them to the directory corresponding to the URL
http://nerdy-deeds.com/facebook/test-app-1.
appinclude.phpWe’re now going to create a file that creates an instance of the Facebook class and does some other initialization. This file will be included at the start of any PHP pages we create in our application.
Copy the code below:
<?php
require_once 'facebook.php';
// TODO: Fill in the API key for your app below.
$appapikey = '[your api_key]';
// TODO: Fill in the secret for your app below.
$appsecret = '[your secret]';
$facebook = new Facebook($appapikey, $appsecret);
$user = $facebook->require_login();
// TODO: Change the URL below to the callback URL for your app.
$appcallbackurl = '
http://nerdy-deeds.com/facebook/test-app-1/'; //catch the exception that gets thrown if the cookie has an invalid session_key in it
try {
if (!$facebook->api_client->users_isAppAdded()) {
$facebook->redirect($facebook->get_add_url());
}
} catch (Exception $ex) {
//this will clear cookies for your application and redirect them to a login prompt
$facebook->set_user(null, null);
$facebook->redirect($appcallbackurl);
}
?>
You’ll need to make three changes, each marked by a comment beginning with TODO::
* Provide your API key
* Provide your secret
* Provide your application’s callback URL
Save the file as
appinclude.php and FTP it to your server, into your callback URL directory.
Finally, Some Application CodeNow that we’ve done all that setup, it’s time for the fun part — writing some actual application code!
Let’s start with something simple, which I’ve cribbed off the
Step by Step article at developers.facebook.com:
<?php
require_once 'appinclude.php';
echo "<p>hello $user</p>";
?>
Save the file as
index.php and FTP it to your server, into your callback URL directory.
Once you’ve done that, let’s try the application out. Let’s try it at your server first — enter the callback URL into your browser’s address bar. In my case, that’s
http://nerdy-deeds.com/facebook/test-app-1.
You should see something like this:

In my case, the text output was
hello 563885607; 563885607 is my Facebook user ID. In your case, the number will be your user ID. (If you want to confirm that the number is your user ID, log into Facebook and click the Profile link at the top of the page; your ID will be the parameter in that URL.)
Now let’s try it inside facebook. Enter your Canvas Page URL into your browser’s address bar. In my case, that’s
http://apps.facebook.com/joeydevilla-a.
If this is the first time running your app within Facebook, you’ll have to click on the
I Agree button to accept the terms of service and then click the
Add [your application name] button to add it to your profile.
You should then be sent to a canvas page that looks something like this:

Clicking on the
Profile link will take you to your profile page. Your app should appear in its own
profile box somewhere in the wide column — scroll down if you don’t see it at first. Here’s what my app looks like on my profile page:

“Hello there, children!” is what I entered into the
Default FBML field in the
Installation Options part of the
New Application page. We’ll cover changing the contents of your app’s profile box later.
First, let’s see what we can do about being greeted by name rather than by user ID…
FBMLFBML is short for
Facebook Markup Language, which they describe as “an evolved subset of HTML from which we have removed some elements, and added others which are specific to Facebook.” It’s documented at the
FBML page at developers.facebook.com.
One of the Facebook-specific tags is
fb:name, which is described in the documentation as:
Expands to a user’s name.
Attributes: *
uid - Facebook user ID.
*
firstnameonly - Show only the user’s first name. Values: true, false. Default: false.
*
lastnameonly - Show only the user’s last name. Values: true, false. Default: false.
*
possessive - Make the name possessive (”Joe’s” instead of “Joe”). Values: true, false. Default: false.
*
useyou - Substitute “you” if the ID is that of the logged-in user. Values: true, false. Default: true.
*
ifcantsee - Alternate text to display if the logged-in user can’t see the specified user.
Let’s make a small change to our application and wrap the
fb:name tag around the $user variable:
<?php
require_once 'appinclude.php';
echo "<p>hello <fb:name uid=\"$user\" useyou=\"false\"/></p>";
?>
(Note that there is no whites pace in before the closing / in the FBML tag. Facebook doesn’t like those and will throw up an error message if you include such white space.)
The idea is to output the HTML <fb:name uid="
user number goes here” useyou=”false”/>. Here’s what it looks like when I run the page on my own server:

That’s no suprise. If you view the source of your page, you’ll see that the fb:name tag is still there. Since your server most likely doesn’t have an FBML parsing/rendering engine, the tag is displayed as is, and your browser ignores it.
Your application’s canvas page is in Facebook, which
does process FBML. Here’s what it looks like:

As you can see, the FBML got processed, and my name appeared instead of my user ID.
Getting Information About MyselfThere are a lot of interesting methods within the FacebookRestClient class, and the inline documentation should be enough to get you started.
Let’s take a look at the
users_getInfo() method. Given these 2 arguments:
* An array of user IDs (integers)
* An array of field names (strings)
users_getInfo() returns the values of the given fields for the given users.
The question is now “What are the possible fields?” If you scroll down to the very end of the
facebookapi_php5_restlib.php file, you’ll find the following definition:
$profile_field_array = array(
"about_me",
"activities",
"affiliations",
"birthday",
"books",
"current_location",
"education_history",
"first_name",
"hometown_location",
"hs_info",
"interests",
"is_app_user",
"last_name",
"meeting_for",
"meeting_sex",
"movies",
"music",
"name",
"notes_count",
"pic",
"pic_big",
"pic_small",
"political",
"profile_update_time",
"quotes",
"relationship_status",
"religion",
"sex",
"significant_other_id",
"status",
"timezone",
"tv",
"wall_count",
"work_history");
Let’s take this method out for a spin. Let’s fetch my birthday, picture and favorite movies. Here’s what the code looks like:
<?php
require_once 'appinclude.php';
echo('<pre>');
print_r($facebook->api_client->users_getInfo(array($user), array('birthday', 'movies', 'pic')));
echo('</pre>');
?>
Here’s the application’s output (it’s the same at both the callback and canvas page URLs):
Note that list-like items, such as movies, are delimited with carriage returns. That’s why I put the output between
<pre> tags: so that the carriage returns would be rendered.
(To be honest, I haven’t seen Let’s Go to Prison. I hadn’t filled my movie list prior to this exercise, and for some reason, — probably because the trailer for it made me laugh out loud — it came to mind.)
Who are My Friends?The
friends_get() returns a list of the current user’s friends. Try this code out:
<?php
require_once 'appinclude.php';
echo('<pre>');
print_r($facebook->api_client->friends_get());
echo('</pre>');
?>
Here’s a snippet of the output when I run it under my account:
Array
(
- => 1867
[1] => 30059
[2] => 30714
[3] => 218804
[4] => 1004687
[5] => 1219440
[6] => 1417669
[7] => 1600639
[8] => 2011454
[9] => 2102542
...
Setting the Content of Your App’s Profile BoxTo make your app display something in its profile box — that’s its area on the user’s profile page — use the
profile_setFBML() method.
An example:
<?php
require_once 'appinclude.php';
$markup = "<p>This is a test of the <strong>profile_setFBML()</strong> method.</p>";
print_r($facebook->api_client->profile_setFBML($markup));
?>
Run this code, then navigate to your profile page. Your app’s profile box should look something like this:
What Next?Although I haven’t covered enough material for you to write a “ready for prime time” Facebook application, this should be enough for you to start exploring Facebook app development.
I suggest trying out some of the code examples in the Facebook
Step by Step tutorial, looking at the code for the Footsteps application, which is included in the library code and making use of all the reference material at
developers.facebook.com.
This material is a property of Joey deVilla. Please,
visit his great blog for more Facebook stuff.