How to create facebook application using PHP and graph api


February 13, 2011FBML PHP79 Comments

This tutorial will explain how to create a facebook application using Graph api and PHP.For those who are new to Facebook platform you need to learn the basics of Graph api.We are about to build a facebook application you can see a demo here



This tutorial will use PHP code-See PHP tutorials on our site

Introduction to Facebook platform

Facebook allows developers to build applications using facebook platform which  has

FBML – Facebook Markup language

FQL – Facebook Query Language

FQJS – Facebook JavaScript

These are basically derived from standard HTML,SQL and javascript to suit the facebook environment.Other than this you need to knoe how the facebook environment is built.Each and every element in facebook is easily accessible from “Graph – API ” which was improved version of REST api which was used previously.

Suppose you want to access the profile picture of a person you can simply call this API

This url simply returns the profile picture of the my facebook account.All you need is the name or UID of the person, in this case you can access my profile picture using my UID also.The power of Graph Api is self explained,you dont need to do complex program to do this easy task.

You can easily access information like name,age,gender,location,friends etc I would recommend you to read Graph api documentation.Keep in mind that not all information is accessible you need to get a permission or access token from the user to access it.

Step 1: Create a new application

Our first step to create a facebook application is go to and click “set up new application “.Give your application a name and agree the terms click submit.

facebook application

facebook application

Step 2: Fill in the details of the application

facebook application

You will be directed to this page to fill up the essential details of the application.

Step 3: Fill in the facebook integration

Every application has application ID,application secret key and api key unique to every application.You need to fill in the details like canvas page ,canvas url etc.

facebook application

Note: Kindly use “https” in the secure canvas url.
The canvas page is your facebook application url,you can see your application in that URL.

Canvas URL- Each application is just a simple PHP page which will be hosted on your server and the canvas page simply renders the application inside facebook.In this case I have hosted my files at “”
See about canvas

Application architecture

Step 4 : Complete registration

For now click save changes [you can edit details later ]

Step 5 : Download client library

To get started in programming you need the client library.In this case we are developing in PHP hence download php client library.There are other client libraries for Javascript,iOS,android sdk’s [ see here] .


Step 6 :Upload the library

Create a folder in your server and extract the library files there,The “src” folder has facebook.php which will serve as the client library.

Step 7 : Set defaults

   include_once "src/facebook.php";
   $app_id = 'APPID';
   $application_secret = 'APP SECRET';

   $facebook = new Facebook(array(
  'appId'  => $app_id,
  'secret' => $application_secret,
  'cookie' => true, // enable optional cookie support

Step 8: code

Check whether the user is logged into facebook before loading the application.If the user is not logged in show the $loginurl

if ($facebook->getSession()) {
  $user = $facebook->getUser();
  $loginUrl = "
    &redirect_uri= URL/
    echo '<fb:redirect url="' . $loginUrl . '"></fb:redirect>';

Step 9 : Fetch details

The concept of this application is to display all the profile pictures of your friends in single page

First get the UID of the current user loggin by calling the function getuser()

$uid = $facebook->getUser();  //get the UID of the current user
$me = $facebook->api('/me/friends');   // access all the information of friends

// $me has the JSON detail of all the facebook friends of the current user

echo "Friends collage";
foreach($me['data'] as $frns)
// Display the picture of friends one by one
echo "<img src="".$frns['id']."/picture" title="".$frns['name'].""/>";

Step 10 : Complete coding

   include_once "src/facebook.php";
   $app_id = 'APPID';
   $application_secret = 'APP SECRET';

   $facebook = new Facebook(array(
  'appId'  => $app_id,
  'secret' => $application_secret,
  'cookie' => true, // enable optional cookie support

    if ($facebook->getSession()) {
    $user = $facebook->getUser();
    $uid = $facebook->getUser();
    $me = $facebook->api('/me/friends');
    echo "<br />Total friends".sizeof($me['data'])."<br />";
    echo "<br /> Friends collage<br /><br />";
    foreach($me['data'] as $frns)
    echo "<img src="".$frns['id']."/picture" title="".$frns['name'].""/>";

    echo "<br /><br /><br />    By <br /><a href=""><img src="" title="Jeyaganesh"/></a>";

    else {
    $loginUrl = "
    &redirect_uri= URL/
    echo '<fb:redirect url="' . $loginUrl . '"></fb:redirect>';  


After saving the file.Proceed to your canvas URl to see the demo of your application[] you can submit to facebook app directory after 10 people start using your application.

I have created one other tutorial on how to build facebook application using facebook query language.

Step:11 Outcome


Access permission for first time user

Download source code

You can follow us on Twitter or join our Facebook Fan Page for more Facebook apps.

Developer Link

Graph api
Canvas Tutorial

79 Responses to “How to create facebook application using PHP and graph api”
  1. Rohit Batra

    thanks for sharing this whole tutorial…will be very clear and helpful… 🙂

  2. Michel H

    A very clear tutorial, perfect for novice users. However, it seems I’m too novice as it’s not working for me. When I access my app, I just see a blank canvas. I’m not redirected to the login/permissions page. When I view the frame source, all I see is the “<fb:redirect url" bit. When I open this URL I do get the login page, but it doesn't open for itself. Any idea what could be causing this?

    Also, in your screenshot you specify the http canvas URL as secure canvas URL as well. When I do the same, Facebook says the URL needs to be https (which makes sense).

  3. Michel H

    Ah I’ve already figured out what the problem was. It’s important to know that the default canvas type is set to IFrame, not to FBML. In order for the fb:redirect to work, you will of course have to change the canvas type.

  4. Kunal Panchal


    Great work done in this blog post, but here are some corrections which you need to do and which will help to others to follow it in ease.

    1. In this image the secure field would stay empty as there is no https in tht url which you have shown – 3.facebook-application.png

    2. URL/
    Please notify it some where that we also need to edit these values in url like APPID and CANVAS URL

    3. in the Complete code snippet you have missed this
    >>>> echo ”;

    And just cause of this few missing informations i lost an hour in finding the prb. 🙂
    But did learnt some new error ways. Please update it, as you blog is good.


    • Miro


      I would need a help with an application,, random image script I need for FB.. can u help me?


  5. Jeyaganesh

    Thanks kunal.Good you liked our blog.

    Thanks for pointing out the “https” error I have mentioned the change below that image.I find some issues in displaying code here so its better to follow the complete code via the link “”

  6. berko


    In your sample we see that you have entered “http” instead of “https” at the input of
    Secure Canvas URL.
    When i try to do it i get an error that i need “https”.
    Appreciate your explanation.

  7. jordan

    How can i post a picture to a users profile, say as their profile picture or as a comment to look at their new picture?

  8. Akshay B

    D tutorial is great, yaar!
    I want to create an app fr a group. N in d developers.facebook documentation i found dat, we need to an object of ‘group’.
    How can I create object of a group. Can u demonstrate?

  9. Robby

    Can you help me with this error when I start my facebook app :

    FBML Error (line 20): illegal tag “map” under “fb:canvas”
    FBML Error (line 21): illegal tag “area” under “fb:canvas”
    FBML Error (line 22): illegal tag “area” under “fb:canvas”
    FBML Error (line 23): illegal tag “area” under “fb:canvas”
    FBML Error (line 24): illegal tag “area” under “fb:canvas”
    FBML Error (line 28): illegal tag “body” under “fb:canvas”

    • Jeyaganesh

      May i know from where are you having your application files? i mean the host?

      after loading the application right click->view source and check whether the application shows you the correct html or not..

      If you are using iframe based app i would advice you to switch to fbml app

  10. Robby

    Thanks for your reply Jeyaganesh..

    I host my files at, i think my host couldn’t handle the request.
    Do you mean the canvas type must be the FBML type.

    And can i test your code at my local server? Is it working correctly?

    • Jeyaganesh

      I guessed that you would be using 000webhost because there is a common problem on facebook apps using that host.

  11. Miguel Angel

    Thank you for the tutorial. I have been testing it and you forgot the IF sentence in the authorization zone:

    IF () <- you forgot this.
    echo "

    By “;

    else {
    $loginUrl = “
    &redirect_uri= URL/
    echo ”;

    Can you add it?
    Thank you again

    • Jeyaganesh

      Hi muguel. The code working i Guess. have you tried the code?

  12. Ahmed Adel

    Also I wanna know how to post to the logged in user wall?
    Pleae let me know ASAP
    send me mail on

    • Jeyaganesh

      You need to authorize app with stream.publish permission ahmed.

  13. Ashok

    Hi all,
    I am on the way of developing the above application, and now facing an error .
    after authenticating (clicking Allow in Request for permission), the browser is looping with the following URLs,
    1. NAME/etc
    Whats wrong with my code.
    Please help me…

  14. Jeyaganesh


    please download our source code from here [] please try this code,it will work

  15. Ashok

    Thank you Jeyaganesh, now its works fine….

  16. Ashok

    Hello i got another error also,
    it is looping there after click the “Allow” permission.
    The application link is:

  17. al


    • Jeyaganesh

      sure. what is the issue you are facing?

  18. pavankumar

    Hello sir,
    i cant understand wat i hve to do with the code.i have created a folder in the server and extracted the client library files there.There after is there any modification required in the facebook.php file?if so wat are the modifications i need to do

    • Jeyaganesh


      You dont need to change the facebook.php.Its just the library that is used as is.

      If you need any clarifications kiindly post here.


  19. ricky spires


    great tutorial but i cant get it to work.

    tried your tutorial using that code and i got this error

    Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in D:\Domains\\wwwroot\fb\index.php on line 25

    then i downloaded the code from
    and i get this error

    Fatal error: Call to undefined method Facebook::getSession() in D:\Domains\\wwwroot\fb\index.php on line 19

    it doesnt help that you keep changing your code. its different in your examples and the Step 10 : Complete coding and the code

    im more confused now than ever. what a WASTE OF 3 HOURS OF MY TIME

  20. jeyaganesh


    you dont need to change the facebook.php. it is used as the library for ur application.


  21. Goldie

    nice tutorial. I have a question 🙂
    I have made fb app, and fb developer page show me, that my app Canvas FBML/iframe id iFrame… But, when I have some comments on page, and when I don’t want to have scrollers on middle of page (scroller of iframe), so comments hide under the bottom of frame…

    How can I make app, which is not in iframe? because, I think that scrollers in middle of page – app are horrible 😀 How can I make that scroller will be only one – on right hand side of web browser, and comments will show under the app – all comments – and any comment wouldn’t be hidden on bottom of frame…?

    I am sorry – my english – I didn’t write and speak for loooong time in this language, so sorry please about this :))

    • Jeyaganesh


      Please try creating FBML app instead of iFrame.


  22. AShutosh

    i followd your tutorial, as written pretty well, but i got some errors, can you described what it means,i am still learning php and facebook api

    Thanks, I paste the errors

    Warning: include_once(/app/lib/facebook.php) [function.include-once]: failed to open stream: No such file or directory in /home/adatar/public_html/app/index.php on line 9

    Warning: include_once() [function.include]: Failed opening ‘/app/lib/facebook.php’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/adatar/public_html/app/index.php on line 9

    Fatal error: Class ‘Facebook’ not found in /home/adatar/public_html/app/index.php on line 13

    i hosted the pages in some free hosting site… i little bit confused about the which folder should i put my index file and facebook.php file.. and then what will be my canvas url??

    Thanks in advance..

    • Jeyaganesh


      Have you mentioned the correct URL of your FB app? (including “/” at the end ?)


      • ankur

        Hi JeyaGanesh,
        I am gettin the same error.
        I have included the facebook.php file locally.

        this is something which I am doing

        but its still throwing the same error:

        PHP Fatal error: Class ‘Facebook’ not found in /mnt/releases/server/asrivastava/first-task/390f5294f2b74ffbbe729e1ce9773c39573973b8/public/subscribe.php on line 26,

        • ankur

          I missed this line ,
          include_once “./php-sdk/src/facebook.php”;

  23. albertcsa

    i tried your sample code with 3.1 sdk

    Call to undefined method Facebook::getSession()

    • Jeyaganesh

      Hi, please activate the errorLog() function and see the detailed error message.


    • Rod

      I was having the same issue. I found this in :
      If you’re currently using the PHP SDK (v2.2.x) for authentication, you will recall that the login code looked like this:

      $facebook = new Facebook(…);
      $session = $facebook->getSession();
      if ($session) {
      // proceed knowing you have a valid user session
      } else {
      // proceed knowing you require user login and/or authentication

      The login code is now:

      $facebook = new Facebook(…);
      $user = $facebook->getUser();
      if ($user) {
      // proceed knowing you have a logged in user who’s authenticated
      } else {
      // proceed knowing you require user login and/or authentication

      So I replaced the getSession with getUser and it seems to work.

      • Scott

        Are you still using this same code for this app?

        I made these changes and this still doesn’t work.

        I am not getting the dialog box asking me to grant permissions to this app.

  24. Priyanshu dubey

    it is very helpfull for us..

    Priyanshu dubey

  25. Tong Peng

    Wow this is a wonderful demo/tutorial.
    However i have some questions as i have recently been tasked to develop a facebook application for my school.

    1) To develop a facebook application, does it have to be a web application hosted somewhere else using web languages like PHP/JSP etc??
    2) Can it also be a desktop application developed using Java and then hosted on a server page before loading into facebook??
    3) What would be a better choice, PHP or JSP to communicate with the facebook APIs, in terms of accessibility and ease of development??

    Is there a way to retrieve the RSVP activities posted by all the friends of a particular user??

    Any help is appreciated!! Thanks.

    Tong Peng

  26. Rahul

    I m unable to create a fb app, fb is saying to register mobile number or credit card, but my mobile number is already registered.

    any suggestion??

    • Jeyaganesh

      Hi rahul,

      I found this solution from facebook forum (
      go to account settings, the mobile tab and then go through the process of texting ‘F’ to the number and then try creating an application.
      Hopefully it works for you.

  27. shiv

    hi Jeyaganesh,
    Thanks for this excellent post. Quite new to web and facebook development I had been struggling for a few days now when i hit this page. The problem is my application is still failing. Could you please help to suggest some thing here.
    I have exactly used the code you have provided ( just with change of application-id/secret). I was not sure how to write a index page so i wrote a index.php ( and copied the code you have in friends collage in it). Still when i use the FB app or use the link in the browser i get a listing of my directory content rather than the application permission page. My application can be accessed via

    you would see a banner on top, that a result of the free hosting that i am using. Probably this is a result of my free hosting provider not supporting php files in some way. Could you please comment.

    Could you please share your index and fbmain files as well. Also do you have a index.php there or index.html. Apologies for my basic doubts but i am quite a starter for web.

    Thanks & Regards,


    • Jeyaganesh

      Hi Shiv,

      Many free hosting providers doesn’t allow fb apps,you can see from previous comments that the free host can’t handle the fb app request.

      The file here( is the index.php file which is used in this application.

      Thanks for reading Devlup

  28. James


    Thanks for the tutorial, really cleared up some of my confusions.

    However, please go back and fix some of the typos. One, your box code is different from the “complete code” you have listed, which has an extra ” after the first img src.

    Second, please make a note that getsessions is now getUser.

    • Jeyaganesh

      Thank you James for pointing out.It happened due to the syntax highlighter plugin.

  29. U Tanna

    Hello Jeyaganesh,

    I am facing some unique problem in fb app.
    Recently we have shifted our fb app server to another server
    We have installed lamp server on new server and copied all files in that new server and also changes all pointing to new servers.

    But when we tried to open app it is showing us “Failed to load source for:

    Please help

    • Jeyaganesh

      Hi Tanna,

      Please cross check
      1.whether you have copied all the files required for the app to new server.
      2. The configuration of new the server.

      If nothing works out, try to create new fb app pointing to your new server.


  30. manoj

    hi jeyganesh,
    thanks for your excellent post. while i tried your method for my app, i encountered a fatal error.

    “Fatal error: Call to undefined method Facebook::getSession() in /home/public_html/index.php on line 14”

    as i am new to web i don’t know about these kind of errors.
    so please help me in this issue.
    thank you.

  31. satikin

    Thank you so much for this tutorial! I was reading and reading about open graph on facebook developers page but i didn’t know how to use it… very good job!!!

  32. Mali

    Hi all, please help for finding canvas url, page url, i can not find or creat it. what shoul i do? thank you.

  33. dev

    Hi ,

    I tried to create an application but am getting a blank screen, can you please help me.Moreover Canvas FBML/iframe is comming as iframe , where can I change that.

    Please help me I wasted almost 4 /5 hours and still wondering how to fix it.

    Thanks in Advance

  34. Ethan

    Brilliant tutorial for us beginners.
    I am running my app from a localhost but I keep getting this error:

    Fatal error: Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP extension.’ in C:\xampp\htdocs\f8\src\base_facebook.php:19 Stack trace: #0 C:\xampp\htdocs\f8\src\facebook.php(18): require_once() #1 C:\xampp\htdocs\f8\index.php(3): include_once(‘C:\xampp\htdocs…’) #2 {main} thrown in C:\xampp\htdocs\f8\src\base_facebook.php on line 19

    Can someone point out where I am going wrong? I’m very new at this.

    • Jeyaganesh

      go to xampp/php/php.ini  
      find the word “extension=php_curl.dll”
      remove the ‘;’ before the line

      This will enable curl extension for xampp.

      • sabiru

        I’m getting the same error and did remove the ; before extension=php_curl.dll in the php.ini but am still getting the same error message. If there anything else that I can do?

  35. Xenox

    Tried this tutorial, seem everything is working good but I get a blank canvas. sucks can’t see nothing really. what do i do now?

  36. Jeyaganesh

    Please check the canvas URL.Do you have “/” at the end.?

    • Xenox

      yes I do. I’ve got a “/” at the end of the secure and canvas pages

  37. Arvindh

    After a user lands on my , i have link which redirects them to,read_stream” target=”_top”.

    However, after authenticating, they are redirected to while I need them to go to

    How can I do this? I changed the redirect_uri parameter to but that throws up an error.

    Please help me out!


  38. CoolZam

    I want to create a facebook cover site like and

    I am completely new to Facebook developers area. So, could you please inform me how to achieve the same.

  39. Ankur Thakur

    Hello Buddy,

    Thanks for this great tutorial. I understood everything that How to use and grab the info from facebook.
    The only thing which I am no able to do is to properly authenticate my App in facebook.

    My App is a Canvas app, say :
    And the Canvas URL from my Domain for it is :

    Now, When I am authenticating the User using the Login URL which you are using in the Code, Its showing me access_token in the URL like this :

    So any idea what is the matter with that ?

    I have seen in some other Apps and they don’t get this access_token in URL. Any Idea what they actually do ?

    Thank You for this great tutorial.

    Ankur Thakur

  40. Miro

    who can help me with my application? contact me to




  41. Freddy Hidalgo-Monchez

    Awesome tutorial! I’m at a facebook hackathon and this has been helpful!

  42. sumit rana

    hey jayeganesh,
    i am getting an error bro what should i do,form last 3 hours i am wondring on this error only plz do somthing dude check out the error on the below link:-

    “404 Not Found

    The server can not find the requested page: (port 443)

    Please forward this error screen to‘s WebMaster.
    Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8e-fips-rhel5 mod_fcgid/2.3.6 Phusion_Passenger/3.0.9 mod_bwlimited/1.4 Server at Port 443″

  43. catlingo

    Thanks for this tutorial. This got me going a bit. I had to tweak it to almost make it work.

    Here’s some issues:
    1) The code still has getSession instead of getUser and will render a blank page. Making the replacement stopped the blank screens.
    2) the last echo doesn’t render in the IFRAME, so I replaced it with
    echo ‘Login with Facebook‘;

    which sometimes works

    Sometime, I get the tiles of my friends images, other times I need to click my added login link and I get the msg:
    “error”: {
    “message”: “Error validating application.”,
    “type”: “OAuthException”

    How do I make it work every time?

  44. musi

    What a great tutorial!

    However, I am getting a blank page after trying these steps.

    ” else {
    $loginUrl = “
    &redirect_uri= URL/
    echo ”;

    I am getting this after I view the page source.

    1- I am testing it using localhost (xampp), is it correct?
    2- Do I need to give APPID, CANVAS URL values? and from where I can get CANVAS URL?

    Thank you,

  45. KnierSchleiff0205

    Just wanna comment on few general things, The website style and design is perfect, the content material is very superb : D.

  46. Pratik Ghela


    This tutorial is superb. But after hours of cracking my head, finally I found out that FBML is no longer exiting for new APPS. So, can you tell me how to use this in iFrame?

  47. habib

    Hi ,

    I tried to create an application but am getting a blank screen, can you please help me.Moreover Canvas FBML/iframe is comming as iframe , where can I change that.

    Please help me I wasted almost 4 /5 hours and still wondering how to fix it.

    Thanks in Advance

    • Jeyaganesh

      The application code is working fine for me.This app is live on facebook and I don’t see any problems.Please follow the steps clearly and retry once more.

  48. Guna

    I tested your demo application,its work wonderful but i facing below error when i use your code.hope you can help me.thank u in advance.
    Fatal error: Call to undefined method Facebook::getSession() in /home/santacom/public_html/facebook/index.php on line 14

  49. pankaj gupta

    correct this plz,
    Fatal error: Call to undefined method Facebook::getSession()

  50. prasad

    My server supports only http connection, it doesn’t support https.
    But it says that it supports only https connection. What can i do??

    • Abhilash nayak

      Instead of creating apps on Facebook canvas.. you could try building apps on websites. which requires FB login.

      P.S you require CURL support for php .

Leave a Reply