Build Your First Facebook App

Build Your First Facebook App

Tutorial Details
  • Difficulty: Advanced
  • Completion Time: 1 Hour

So you want to build a Facebook application and reach literally millions of users. Well luckily, writing an application using the API isn’t too hard to learn (for the basics, anyway). In this tutorial we will write a Facebook app that generates a random quote to display on the user’s profile.

Getting Started

It’s worth noting that the Facebook API is available to a number of languages, all listed on the Facebook Developers Wiki. I will be using PHP 5 for this tut. You will also need to download the PHP 5 Client Library, which I’ve included in the SRC files. All code featured here will be in the index.php file.

Step 1: Initialize Your App

The first step to get a Facebook API key, which allows your app to retrieve information from Facebook. Go to the Facebook Developer Application and click the “Set Up a New Application” button. Pick a name, agree to the Terms & Conditions, and you’ve got your API. Now you need to set up your canvas page name and callback URL.

Your canvas page is the application area within Facebook; the name is added to the URL and will look like this: http://apps.new.facebook.com/[YOUR APP NAME]. The callback URL points to the server hosting the app files. To set these up, from the “My Applications” page click “Edit Settings” on the right hand side. You will see the fields to fill in both, as I did in the screen shot below. While there are lots of other options, none are necessary for this tutorial. Click ‘Save’ and you’re now ready to build your first Facebook app. Facebook even provides you with some start up code. I’ve cut out the extra stuff and gave you only what you need to initialize your app…

<?php

require_once 'includes/facebook.php';

$appapikey = '85e4cd7042467d0b20109aafb6f20117';
$appsecret = 'be5a528d73ad191b6b21a84c4af054ee';
$facebook = new Facebook($appapikey, $appsecret);
$user_id = $facebook->require_login();
$callbackurl = 'http://www.casabona.org/nettuts/';

?>

This is fairly straight-forward code. We create a Facebook object using our API key and app secret, which was given to us when we created the API key. The first thing we do after that is get the user id of the logged in user. This will be valuable to us if we were do things get the user’s name, the user’s friends, etc. I’ve also added the $callbackurl to make it easier to link to images or other files, as Facebook does not allow relative linking.

Step 2: Writing the Application

If we don’t make specific Facebook calls, this is just like writing a php application. Below is our code.

//initialize an array of quotes
$quotes= array("Only those who dare to fail greatly can ever achieve greatly.", "Take my wife. Please!", "I believe what doesn't kill you only makes you... STRANGER");

//Select a Random one.
$i= rand(0, sizeof($quotes)-1);

//print the CSS
print ('
<style type="text/css">
 h1{ margin: 10px; font-size: 24pt; }
 h2{ margin: 15px; font-size: 20pt; }
</style>
');

print "<h1>Nettuts Quotes</h1>";
print "<h2>". $quotes[$i] ."</h2>";

This is all you need to do to print to the canvas page. One thing to note is the way we create CSS. We cannot call a file like style.css- we actually have to include the CSS in the HTML. This is so our CSS doesn’t interfere with Facebook’s. You should also know that when styling divs, you can only uses class, not id. The code we created will produce something like this:

Step 3: Creating the Profile Box

Finally, some Facebook specific stuff. The code below is necessary to add our quote to the user’s profile, granted they are displaying our app in their profile. In our app, I’ve added the follow code right below $i= rand(0, sizeof($quotes)-1);

//prepare string for profile box
$text= ('
<style type="text/css">
 h1{ margin: 10px; font-size: 24pt; }
 h2{ margin: 15px; font-size: 20pt; }

</style>
');

$text.=('<h2>'. $quotes[$i] .'</h2>');
//set profile text
$facebook->api_client->profile_setFBML($text, $user_id);

Notice I’ve done two things here: reprinted the CSS and put everything in a string called $text. This is because the function that sets the profile box text, profile_setFBML, takes two arguments: the text that should go in the profile box, and the id of the user. Any CSS defined for the canvas page is not transferred to the profile, so we must also add that to our first argument. The end result is this:

That’s It!

We’ve obviously only scratched the surface as far as Facebook application development goes. However, with the Wiki and resources Facebook gives you when you get an API key, you should be well on your way to creating the next big app! If you want to check out this app in all its glory, you can go here, just so long as you have a Facebook account.

Joe Casabona is jcasabona on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • narsah

    I think this Tutorial points to the old facebook-api. The new api is not backward compatible.

  • jarski

    How can i add publish_wall permissions as you have in your example app?

  • Pingback: Build Your First Facebook Application in PHP « Php, mysql, ajax, jquery, javascript, css, html – Itzurkarthi's Weblog

  • Pingback: How to Make Money on Facebook? » Earning Spider

  • http://piyushshekhar.com Piyush Shekhar

    Great tut for a beginner like me :)

  • http://adventistsinglesdating.com Jenny

    Thnx… simple and easy to understand!

  • Salah

    thank you for this Great work

  • http://www.onlineworkidea.com iffi

    Can i get few low level application tutorials???

  • http://howto.caspio.com?p=3653 Daniel Cohen

    If you have a Caspio App you can just deploy it directly to Facebook as an app. You don’t need to host a web page. There’s an article about it here

    The basic process is explained again, then you can just use a DataPage.

  • http://funnyfacebook.org/ bento

    is this tutorial using new facebook graph API?
    I love more facebook API tutorial.

    tnx

  • http://www.uhuruafrica.net/RandomQuotes Josephine

    Well I got up and working to an extent but something seems to have gone wrong for me in the quotes section. As I am showing all the quotes instead of one quote. I have trawled through it a few times checking for parse errors but am not sure if I have missed a command or something or deleted one by accident or something. I tried copying the source file parts again for the index page aside from my new quotes but cant seem to get it working correctly. Sorry great script though had it up and running in five minutes aside from the problem I am having.

  • Daniel

    Doesn´t work…
    “PHP Fatal error: Uncaught exception ‘FacebookRestClientException’ with message ‘Unknown method’ in /***/includes/facebookapi_php5_restlib.php:1734″

    Any update to this code..?

  • http://www.ukessayhelp.com UK Essay Help

    its great post to learn about facebook application.

  • http://websinkers.com Param

    Lovely, I am looking for more information to make more advanced application. This tutorial is a great start. Thank you for sharing.

  • Tanha

    Hi,

    Great tutorial.

    I followed exactly what you mentioned, but I have problem open the app an error as follow occurs:

    Error while loading page from URL

    It seems I am using the OLD library, can u please explain what is wrong?

  • Vivek

    But how to give “Request for Permission” if user login 1st time in your app.

  • http://www.rightlog.com Sam

    Great tuts for starter. Thanks for sharing

  • Rio

    help me please!!!!!!!!!!!!

    why cant i connect to facebook server???

    when i want to try connect, the page looks like this

    Warning: fopen() [function.fopen]: URL file-access is disabled in the server configuration in /home/vol13/xtreemhost.com/xth_7963177/htdocs/includes/facebookapi_php5_restlib.php on line 1816

    Warning: fopen(http://api.new.facebook.com/restserver.php) [function.fopen]: failed to open stream: no suitable wrapper could be found in /home/vol13/xtreemhost.com/xth_7963177/htdocs/includes/facebookapi_php5_restlib.php on line 1816

    any idea???

    thanks before

  • Aniruddha

    This was nice..helped me build apps.http://facebook.com/disturbyourwedding !! :) Thank you

  • Pingback: Colección de enlaces sobre desarrollo para Facebook | Chalchicha.es

  • Mohammad Shabaz

    this wont work anymore…
    profile_setFBML() is a removed standard..!

    Hence the fatal error

  • michael

    a new more advanced facebook app would be awesome.

  • thuypv

    I do follow this tutorrial, but in my application don’t work. It show error : Empty response received
    How i can fix this error

  • http://www.sarfraznawaz.wordpress.com Sarfraz Ahmed

    I am sure you must have built it quite some time ago. The application now gives error:

    Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in E:\inetpub\vhosts\admin.cyber.net.pk\httpdocs\webs\facebook\includes\facebook.php on line 38

    • Sanjeet

      Yes. I too get the same error!

  • Cameron Reid

    Great Info. You can use Caspio-Powered Facebook Apps to help create any type of business app and easily integrate it into your Facebook business page without coding. Check it out: http://blog.caspio.com/integration/create-a-custom-facebook-application-for-your-business/

  • http://kangaroojack.net/ sanzdee

    Fatal error: Uncaught exception ‘FacebookRestClientException’ with message ‘Unknown method’ in //facebookapi_php5_restlib.php:1734 Stack trace: #0

  • http://www.netframework4.com Net Framework 4

    good thanks for helping us i wanna make fb apps

  • Pingback: تاپ لینک هایی در مورد برنامه نویسی

  • http://lucaskreutz.com.br Lucas Kreutz

    Great article!

    Unfortunely, the demo is broken.

  • http://www.gusdecool.com/ GusDeCooL

    Outdated

  • http://www.anil2u.info Anil Kumar Panigrahi

    Please help me on this.

    I want to publish a message to my facebook page using API. While fb-login I get the permission of publish_stream, manage_pages.

    Using below code I am able to post the message

    $facebook->api(“/[Page Id]/feed”, “post”, “[Message]“);

    But It is not displaying in the wall of page. When I login to that fb page ( Created page with different login details ) then only display those post message as Recent Posts by Others on [ Page Name]

    ‘subscriber’ or ‘like’ users cannot get posted message. How can we rectify it so that I will integrate it into one of my website admin section.

    Thanks in Advance.

  • Jayasankar.K

    hi,
    I want my frst facebook app.

  • pratik

    plz give the latest ways to do stuff’s. the tutorials here are pritty much out of date. plz do so if u can. thank u

  • sarunathan

    This link -http://www.webtuts.info/webdevelopment/facebook-api-integeration/143/ has some resources with new graph api using javascript sdk.