Try Tuts+ Premium, Get Cash Back!
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
  • http://harmin-online.blogspot.com/ Harmin

    Can I change my background profile llike in FS??

  • Benoit

    I come here everyday but never post comments…

    You know what could be awesome? Merging the present tut with “create an OOP blog with php”. There we would have an enhanced starting point ;)

  • chris

    Contact me id like to talk to you about you developing a basic fb app for me

  • http://www.filipejorge.com deejorg

    I don’t understand where i put the profile box code. I can add the profile box but can’t show content. Any help?

  • alex

    or you can do this
    You may think that building a facebook app is very hard, well its kinda easy with this new appliation we added

    your going to need to add two applications for this two work

    first add Facebook Developers
    http://www.facebook.com/developers/

    Next add The Stealthrouter App Builder
    http://apps.facebook.com/stealthrouter/

    Go to stealthrouter app builder and then click *Use an app wizard*

    Next select a wizard

    name it, and add a description

    Now its going to ask for a couple things like

    API Code
    Facebook Secret
    Canvas URL

    Go to facebook developers and click set up new application

    Name it the one you named already

    and copy the API ID
    and paste it in The API Slot in the stealthrouter app builder

    Next Copy the Facebook Secret and paste that into the facebook secret slot in the stealthrouter app builder

    Now to the canvas url

    go to facebook developers and click canvas and make it what ever you want

    like for us we made it apps.facebook.com/stealthrouter

    now copy the end part of your canvas url

    and paste it into the stealthrouter app builder under canvas url, so we would paste stealthrouter

    next it will give you a canvas call back url

    copy it form the stealthrouter app builder and paste it into the facebook developers

    to do this

    go to canvas and paste it in canvas call back url

    now visit your application and it should work

    example

    http://apps.facebook.com/stealthrouter/

    • jova

      great!

      put how i can setup profile box content url?

      have i write it in separate file or in index file?

      I’m really confused ..

      Thank you in advance,
      jova

  • http://www.itsyllabus.com MIKE

    i am goonna write one to check it myself:)

  • http://tuts.cgbaran.com CgBaran Tuts

    Awesome tutorial gotta try a variation soon

  • http://www.albert-pak.com Albert Pak

    Nice tutorial, been thinking about writing a Facebook app for awhile now :) Great start with this one. Would be nice if there would be more Facebook app tutorials.

  • Z

    can i do it like this ?

    //initialize an array of quotes
    $quotes= array(” OWN TEXT”); ??????

    • Z

      can i do it like this ?

      / / i n i t i a l i z e a n a r r a y o f q u o t e s
      $ q u o t e s = a r r a y ( “ O W N T E X T ” ) ; ? ? ? ? ? ?

    • Z

      sorry I’d mistake for that two.

      can i do it like this ?

      Posting image on every Text is that possible??

      / / i n i t i a l i z e a n a r r a y o f q u o t e s
      $q u o t e s = a r r a y ( ” i m g s r c = ” I M G U R L ” h e i g h t = 1 2 2 w i d t h = 1 6 0 a l i g n = l e f t b o r d e r = 0 O W N T E X T ” ) ; ? ? ? ? ? ? ( “”) these are included but not posted cause message don’t work with that close and open codes

  • Sterling Daniels

    Buy where does the code go and how do you run it? I’m a programming newbie – is it so obvious that I don’t see it? When you type the initial php code that shows where the api key and secret code, where is it stored? How do you get facebook to run it? Excuse the dumb question but no one talks about this part.

    • Chris

      I second this. I have no idea
      1.)what file to put this code in
      2.) what to save this file as (or if the file name even matters)
      for instance, does it need to be named “index.php”….?
      3.) Where to put this file on my server

  • http://www.omairarts.com Omair Rais

    Thank you very much….

  • http://www.thach.us/ SaBinh

    that gave me an idea, thanks

  • http://ariful.wordpress.com ariful

    very nice and simple to understand

  • http://www.stratbeans.com Subodh

    Great Stuff !

  • http://www.webwingz.com Mahesh Bisen

    Great great … awesome

  • Pingback: 網站製作學習誌 » [Web] 連結分享

  • cactusPhone

    Great tutorial.

    Has anyone encountered profile box content when installed on Pages not updating? When I go to apps.facebook.com/myApp/profilebox I see the proper fresh content, but when I install to my page, the profilebox content shows old, not updated content.

  • http://www.simpleabs.com Simpleabs

    Great little tutorial! I am currently developing my first facebook app for simpleabs.com

    Cheers,
    Simpleabs

  • http://largecaptrader.wordpress.com Anonymous

    Warning: require_once(../includes/facebook.php) [function.require-once]: failed to open stream: No such file or directory in C:\X\xampplite\htdocs\index.php on line 4

    Fatal error: require_once() [function.require]: Failed opening required ‘../includes/facebook.php’ (include_path=’.;C:\X\xampplite\php\PEAR’) in C:\X\xampplite\htdocs\index.php on line 4

    I must be the only one who didn’t get it working. New to PhP, i installed the facebook.php in a different directory and can’t get it working. I’m using XAMPP to develop (learn at least), need the tutorial before this on how to set up properly and the path names.

    • jay

      You can’t run the app (facebook as well twitter) from local server ( XAMPP ). You need an online server ( hosting provider )

  • http://www.socialfactory.net facebook application

    thanks for sharing knowledge, it really help me to develop my 1st facebook application.

  • http://www.indiaonapage.com amit

    Thanks for the precious information

  • http://sanskritonline.com Gokul N K

    Hey nice tutorial…

    Just built my first facebook app..

    Damn easy, but a lot learn if you want to build a serious app…

    http://www.facebook.com/apps/application.php?id=207829643803

  • olivia

    what do i write in the code part

    • g

      what
      do i write in the code part because i dont now what to mwrite because im new

  • jaqi vigil

    made my very first facebook app following this tutorial. sure, it’s not much of an app, but this is a fine way to get introduced to the process.

  • http://HVGHVHJVJH MICHAELHOPPER

    I LOVED IT

  • http://salahuddin66.blogspot.com/ Salahuddin Pasha

    Nice work done….

    I just have to update the old facebook library and use this function:
    $facebook->api_client->profile_setFBML(NULL, $user_id, “Hello”, NULL, NULL, $text);

  • suemarie

    thanks a bunch, very helpful!!

  • http://www.newnectar.com Flip

    To insert javascript:
    To insert css:

    You can’t just use the tag…
    Hope that helps

  • Hudey

    Not very helpful at all for a beginner. There needs to be a lot more information about putting the index.php file toghether, uploading it to your server, uploading the facebook-platform files to the server along with your index.php file. I found this extremely hard to follow.

    I have to name my file index.php5 to tell GoDaddy to use PHP5 (otherwise it uses PHP4). I think I figured most of it out finally, but in the end I’m still getting the error:

    Warning: Cannot modify header information – headers already sent by (output started at /home/content/h/u/d/hudey1234/html/facebook/quotes/index.php5:10) in /home/content/h/u/d/hudey1234/html/facebook/quotes/includes/facebook.php on line 418

    But then the quote prints out after this error is listed 4 times.

    • Hudey

      I figured it out. I created my PHP page in Dreamweaver and it added all of the and tags and stuff. There shouldn’t be anything in the document outside of the opening tags. Nothing at all!

      • Hudey

        ugh… the comment system deleted my tags… there should be nothing outside of the opening PHP tag and the closing PHP tag. I had a bunch of HTML file stuff outside of it and that was throwing the error.

  • http://apps.facebook.com/cerebrationitm/ Gaurav

    Great tutorial , I haven’t seen such a great tutorial site before.

  • http://www.socialcubix.com/services/agency-solutionshttp://www.socialcubix.com/services/agency-solutions Facebook Agency

    Very effective tutorial for new bie developers. I really consider it as great guidelines to developed quality apps. Thanks

  • Cool B

    this information is cool if you still have issues with building your first facebook app try out http://www.webyam.com/bookmarks.php?tag=first-facebook-app

  • http://www.socialcubix.com Facebook Developer

    It is Good news for me .create my application own.Today i created my own application after that i promote that application in face book even my friends.

  • pyemachine

    I cant for the life of me getting any joy here. Can not get it to appear or work

  • http://www.codelobster.com Stas

    I recommend also to use free PHP IDE Codelobster PHP Edition for eapid developing Facebook Applications. It has special plug-in for Autocomplete of Facebook JavaScript SDK, PHP SDK, FQL, FBML and Context Help for Facebook’s API.

  • http://adfeed.cn Angus Li

    Thanks for the helpful tutorial… everything is great except the small piece of PHP code is step 2, which could be simplified:

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

    print “”. $quotes[$i] .”";

    This can be simply achieved by using one line of code:
    $quotes[array_rand($quotes)];

  • http://www.mcbwebdesign.co.uk MCB Web Design

    Liking the Dark Knight quote ;-)

  • Dragonsi

    How do I go about making the usual “Do bar type quest 3 times in a row, move on to quest below it” type RPG app?
    That’s what I’m interested in, making a bar quest game app.

  • http://www.lukup.com Remita

    Wanna know how to create apps quickly that run on multiple social and mobile platforms? Join us for a Free to register Webinar- https://www1.gotomeeting.com/register/969121145

  • Dan

    But how do if you want to make a daily app quote? If a user allow it, then a quotation can appear every day. Thanks :)

  • http://quackquack.in ramesh

    hii its really helpfull code..i uploaded ur code to my server and its working fine but when user click on goto application the code has to display request for permission dialog box to allow users to fetch data….my application also disaplying request for permission with out send me email….can u help me how to set send me email in my request for permission dialog box……………

    thank”s in advance

  • http://www.ConvoSpark.com Derek

    Great tutorial!!!!!!!
    Thanks for posting.

  • http://www.olivearth.in/blogs Tarini

    Sounds great. Looks llike exactly what i was searching for. I will try and revert. Thanks.

  • http://www.hearmeclear.com Amplified phones

    Superb facebook tutorial looking forward to see more from you.

  • http://www.cellphoneinn.com latest cellphone

    This is a good start for new beginner like me, but I think there should me some more example need like how to post data on profile etc

    Thanks

  • Pingback: Facebook App Tutorials: Getting Started | tutorials blogs

  • http://www.justwordpress.net justwordpress

    great tutorial, but what about more advanced techniques? like getting user data from his profile and using them on a different site, or requesting access from a user to post news on his wall! how can i achieve that?

  • DarkMan

    Could please someone give me some help?
    I clicked on the Set Up a New Application, but it said i need some kind of vertification code, i added my phone number but didnt get the code, i sent a mail to facebook but no reply.

    And i cant make a new app with out this code, every time i try to make a new one always asking for this code.

    What can id do?

  • viktor

    Hi,
    <>
    Exactly which API do i have to download? There are loads of APIs there in this wiki site.
    thanks!

  • Pingback: Mobile Testing and Social Media Web Dev « William Barnwell