Essential Graph API of Facebook

essential facebook graphFacebook recently updated their platform and added some new graph APIs. In this tutorial I’ll show some important usage of graph api. The examples here I provided as a cook-book format.

If you’re beginner then please read my previous articles:

1. Get total number of  Share of an url

If you integrated facebook share for your site or if any person share your site url (any url) in facebook then facebook will automatically create an open graph object and tracked the number of users who is sharing that via facebook.  Just use below code to know the number of share

       $pagelike = '';
        try {
            $pagelike = $facebook->api("/$urllike");
        catch(Exception $o) {
        echo '<pre>';
        echo '</pre>';

For example if I provided as $urllike it will output

    [id] =>
    [shares] => 628

2. Get brief information of a facebook page

If you have a facebook fan page and wants to know  summary of the page you can use

       $fbpageinfo =   '';
        try {
            $fbpageinfo = $facebook->api("/YOURFANPAGE_ID_OR_NAME");
        catch(Exception $o) {
        echo '<pre>';
       echo '</pre>';

For example I’ve a fan page that’s title is so I just used

$fbpageinfo = $facebook->api("/");

It outputs

    [id] => 314110374728
    [name] =>
    [picture] =>
    [link] =>
    [category] => Local_technology_telecommunications_services
    [website] =>
    [fan_count] => 1524
    ......... AND MORE.......

Facebook Page API Details

3. Publish something that contains link, photo to a facebook page

This solution is very helpful if you want to publish automatically something in a facebook fan page via your application.

//publish in fanpage
        if (isset($_REQUEST['publish'])){
            try {
                  $wallpostpage = $facebook->api('/FACEBOOK_FAN_PAGE_ID_OR_NAME/feed', 'post',
                                      'message' => 'I like',
                                      'picture' => '',
                                      'link'    => '',
                                      'name'    => '',
                                      'cb'      => ''
            } catch (FacebookApiException $e) {

Just change the parameters and the FACEBOOK_FAN_PAGE_ID_OR_NAME

For example I just posted using my application.

$facebook->api('/', 'post', array(......));

Facebook Post API Details

4. Upload photos in your profile or any particular album that you own

Please keep in mind that you could only upload photos in your profile or your albums via application.  A typical scenario of this would be, you’ve a website where people are logged in via facebook connect. In that site there are many photos and your user may wants to upload some of photos in his facebook album.

When you’ll create $facebook object then set ‘fileupload’ => true

 $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,
      'fileUpload' => true

Use below code, if you provide album id then the photo will be uploading in corresponding album otherwise the application will create an album and will upload photos on that. Please remember, ‘source’ should be absolute file path not be any url. And you must have to provide the ‘@’ symbol before filename. Suppose your php code is in /var/www/ folder and the image file is also in /var/www/ folder. Then just use source => ‘@filename.jpg’

$albumID    =   isset($_REQUEST['albumid']) ? $_REQUEST['albumid'] :  'me';

try {
    $uploadstatus = $facebook->api("/$albumID/photos", 'post',
            'source'  =>  '@FILENAME',
            'message' => 'Messsage'
} catch (FacebookApiException $e) {

Facebook Photo API Details

5. Read comments/like of a post or photo

Every post or photo or album has an id, so using that id you can easily retrieve data. Suppose you want to retrieve recently your tagged photos. Then you can do so…

       try {
            $photos = $facebook->api("/me/photos");
        catch(Exception $o) {
        echo '<pre>';
       echo '</pre>';

You’ll see recently your tagged photos. Now In the output you’ll see each photo has an ‘id’, so if you want to read comments of that id just use

       try {
            $photo = $facebook->api("/PHOTO_ID_OR_ALBUM_ID_OR_POST_ID");
        catch(Exception $o) {
        echo '<pre>';
       echo '</pre>';

6. Create events via php using facebook API

This is super easy. Suppose in your website you want your user may create events then using below code you can do so

try {
    $event = $facebook->api("/me/events", 'post',
            'name'       => 'Facebook Users Party',
            'start_time' => '1272718027',
            'end_time'   => '1272718027'

} catch (FacebookApiException $e) {

Where start_time and end_time would be A JSON string containing an ISO-8601 formatted date/time.

Facebook Event API Details

7. Get total number of like of an URL

If you want to know the total numbers of people who like an URL, you can easily do that the following way. Just use php curl to get the xml output

For example if i just browse

It outputs

<links_getStats_response xsi:schemaLocation="" list="true">

There are many more API descriptions in facebook documention. Like video, user, note, message, group. So just visit facebook documentation and read their API descriptions to complete your requirements.


mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Business | Twitter | Linkedin | Instagram | Flickr | 500px]

You may also like


  • Danil K.
    November 29, 2010 at 5:15 pm

    Informative and useful, as always. Thanks!

  • ccarrasco
    November 29, 2010 at 7:05 pm

    amazing article, thanks 🙂

  • Avedis
    November 29, 2010 at 7:32 pm

    Awesome!… just in time! 😀

  • jasmine
    December 1, 2010 at 3:04 pm

    What is the difference between form processing in ie and other browsers?
    Why aftre clicking the fb:serverFbml there is somting like this in ie: … cbc4%22%7D
    Why there isnt this session in other browsers?

  • Breklin
    December 3, 2010 at 2:43 am

    I am trying to prepare a report for promotions we are going to be running in tab on our page to get the userid’s and date of likes…any input on this? I can’t seem to find a viable solution anywhere.

  • Azzam
    December 7, 2010 at 4:30 pm

    Hi Mahmud,

    I notice that sometimes I share a wordpress post via the like button amongst my friends but that has also been shared by other people ie. on a fanpage. A lot of great discussions goes on but all of these comments are scattered since different people sharing amongst their own friends.
    Q? Is it possible outside of facebook, especially on the original blog post to collate all of those comments?

    Or at the least if the post is shared via a custom custom facebook app [sort of integrates the like button] then maybe those comments can be collected?


  • Marco
    December 16, 2010 at 1:03 pm

    Hi Mahmud, i created a new app and set extended permissions for user_relationship_details which gives me the significant other of the user. I need to be able to get the user’s wife or husband or boyfriend, grilfriend in case the user has one. Even though i set this permissions, once the user authorizes the application, i can’t get the significant_other id, if i do this
    I just get the basic info but not the extendend permissions. I even got the access_token and send it as parameter and still can’t get that additional info. I hope you can help me with this problem since i’ve been looking all over the web and haven’t found an answer. I even tried fql to no avail.

    Thanks for your help

    • mahmud ahsan
      mahmud ahsan
      December 16, 2010 at 10:19 pm

      According to , user_relationships permission is required to get relationship info about your users. As you said you’re not fully success to get info then additionally you could pass “friends_relationships” permission and lets check what happens.

      • Jignesh Sura
        January 7, 2011 at 1:13 pm

        Hi Mahumad,

        I tried to see the whole response object of User API to check whether significant_other data is being pulled or not and it seems like it doesnt pulls that data. The only data that it pulls is the one that is listed on the link given above on the USER object page. I dont know whether its a bug and should be reported or if i am doing it incorrectly then please let me know how to solve this issue.

        I have all the extended permissions possible to get relationship data from user

        Seems like my above comment was in wrong location, This reply is related to comment on significant_user post

  • Boon
    December 17, 2010 at 5:09 am

    Hi Mahmud, great sample and tutorial.

    I want to ask if this works with the migrations on Facebook?

    “If you currently use the fb_sig parameters, you can continue using them for the foreseeable future, but you won’t get new features nor will the documentation indicate how to use fb_sig. If you can, we recommend moving to signed_request.

    “Canvas Session Parameter” has been superseded by “OAuth 2.0 for Canvas”.”

    Thank you Mahmud. =)

    • mahmud ahsan
      mahmud ahsan
      December 17, 2010 at 11:48 am

      If you migrated then you’ll no longer get the session parameters fb_sig_** . But using new sdk you also don’t need those session parameters.

  • Qasim Ikram
    December 21, 2010 at 11:53 pm

    Can you tell how can i get friends List for a user using GRAPH API…… small code will be very helpfull……Thanx

    • mahmud ahsan
      mahmud ahsan
      December 22, 2010 at 12:27 pm

      $facebook->api(‘/USERID/friends’); using php sdk

  • wasi
    January 6, 2011 at 12:23 pm

    please help me. i want to publish on user wall on facebook page tab using facebook api.


  • bob
    January 6, 2011 at 9:42 pm

    Hi Mahmud, great tutorial, very useful, thanks

  • szenma
    January 19, 2011 at 6:00 pm

    please help me i am troubled with this code


    $app_id = “76abd6c860294319cf8062d9457591e”;
    $app_secret = “f445b607085105e6328d806dde80629”;

    $facebook = new Facebook(array(
    ‘appId’ => $app_id,
    ‘secret’ => $app_secret,
    ‘cookie’ => true

    header(“Location:{$facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’))}”);
    include “../admin/control/db_connection.php”;
    $query = “SELECT * FROM `image_dis` where im_subsub=’Krishna'”;
    $result = mysql_query($query, $db) or die(mysql_error($db));

    // $mesd[‘access_token’]= $tok ;
    $mesd[‘message’]= $row->im_des ;
    $mesd[‘picture’]= ‘’.$row->im_file;
    $mesd[‘link’]=$row->im_link ;
    $mesd[‘name’]= $row->im_alt ;

    //publish in fanpage

    try {
    $wallpostpage = $facebook->api(‘/170855269624546/feed’, ‘post’,$mesd);

    } catch (FacebookApiException $e) {

    this is my code
    i want to post under page title nw it posted under developer id so plz help me with rigt example

  • Warmi
    January 26, 2011 at 1:30 am

    Question for mahmud ahsan (or someone knows the answer)
    In another blog (where I can’t leave the comment) I saw you have said:
    “Facebook closed notification system for applications. So you can only send email instead of notifications.” and the question is how can I send emails to user through Graph Api, or did you refer to the old rest api?
    Thanks… !! and forget I reply in this topic 🙂

    • mahmud ahsan
      mahmud ahsan
      January 26, 2011 at 12:56 pm

      Hello Warmi, this is very simple, using extended permission you can get user’s email address. And if you use php just use mail() function to send email in that address.

  • Warmi
    January 26, 2011 at 11:22 pm

    Ah, ok, thank you… I asked you because actually I’m using the Old Rest Api method notification.sendEmail() because of the api didn’t provide us the user email address.. but now I want to migrate to graph api, so I wanted to know how to make this action possible.
    Thanks again…!

  • n8nie
    January 27, 2011 at 1:19 pm

    Hi…I’m trying to get all my tagged photos…
    I tried to use the code u provided…But I’m getting an empty array. Is there smth i missing off??


    try {
    $photos = $facebook->api(“/me/photos”);
    catch(Exception $o) {
    echo ”;
    echo ”;

  • Tihomir
    January 28, 2011 at 3:55 pm

    Dear Mahmud,

    First of all great blog!

    I search net to found way to display fan page founded (created date) .. do you know some way?
    I can’t find any info in documentation and still haven’t ideas in dev. forum.

    Tanks and best wishes,

  • Armin Hierstetter
    January 30, 2011 at 7:51 pm

    Hi Mahmud,

    this just works fine. One question regarding posting on my Fan page. When I post there using your code, it looks like that I posted it rather than my application.

    Is there a way that the post does not show me as the sender but my applcation?



  • amelie
    February 20, 2011 at 3:31 am

    Hi Mahmud,
    I am developing an iframe application and would like to get following details:
    >total application users count till now.
    >whether the application user has liked my application or not.
    Please help me with this.

  • Abubaker
    March 13, 2011 at 11:41 pm

    mahmood, once again like always great post. I would like to ask on thing that is it possible to “make a picture as your profile picture” from within our facebook application through code ? I couldn;t find such thing.. so was wondering whether is it possible to do so….Here is a detailed process that I wanted to have:
    1. User upload a picture (on my server) within my facebook application
    2. Then the user have option to make the uploaded picture as “Make Profile Picture”.

    One thing I came up with was first I will upload that uploaded photo to application album in a User’s account.. After that I don;t have a clue to do ,,,, PLease help..!

    • mahmud ahsan
      mahmud ahsan
      March 14, 2011 at 10:12 am

      Using api you can upload pictures, but there is no way/api to make that as profile picture.

      • Abubaker
        March 14, 2011 at 8:49 pm

        Thank you.. 🙂 This is exactly what I found on facebook developers Forum… How does iPhone do that ? it gives you an option to make an uploaded picture as your profile picture.. ? :S

  • jack
    March 22, 2011 at 12:44 pm


    how create accounts using php curl or any other solution there

  • jack
    March 22, 2011 at 12:44 pm

    how to create facebook accounts using php curl or any other solution there

  • Prash
    May 13, 2011 at 6:19 pm

    I want to know that the way to notify or call a PHP page when anyone share my link and also who share my link.

  • Paul
    May 25, 2011 at 6:00 am

    I am posting to a user’s wall, something like what you have in step 3. I am in iOS, but the basic operations are similar, just done through Facebook iOS SDK calls.

    My question is this: When I do this, the post appears on the wall, but while the link associated with the title of the post is exactly what I asked for, the link attached to the picture has the query string ?ref=nf added to the end. I gather Facebook adds this to tell somebody (?) where the link came from, and it can safely be ignored if you don’t care, except in my case the link is shortened via, and the extra characters break the link.

    I have surveyed my own news feed and see this sometimes and not others. In my own posting, the query string does not appear to be appended if I post directly to the wall, but only when I post through my app.

    Any idea how to suppress the query string on the picture link? Is this something you see as well?

    Thanks for any help you can offer.

    • mahmud ahsan
      mahmud ahsan
      May 25, 2011 at 12:13 pm

      Paul, I’m facing serious problem using iOS sdk and feed publish. Today I checked and found Feed publishing is not working for some of my apps and for some apps feed publish works but only publish to user’s profile wall not home feed. I used the following code for iOS.

      • Paul
        May 25, 2011 at 10:10 pm

        Thanks for your reply. I have not been having any trouble in my app with the feed itself, but the issue I am referring to actually is not iOS specific. In fact, the link that you included, namely

        Shows exactly the issue I am talking about in a web based app. If you scroll to “Example” and click where it says “Click here to try the url yourself”, you’ll get a Post To Your Wall page. If you click publish and then go to your own wall, you will see that the link for the image and the link for the title are different, with the image link including the extra query string. Which is what I want to suppress. So there is something happening in the FB backend doing this that I want to suppress.

        Interestingly, before you publish, you can hover over the image and the title, and the reverse it true. The title link has the extra query string but the image link is clean. Bizarre.


      • sanjay
        June 25, 2011 at 1:27 pm

        Hello mahmud,

        who i know whether user like my application or not..?

  • sanjay
    June 6, 2011 at 3:25 pm

    i tried to get facebook userdata but i got error…
    Exception Object
    [message:protected] => Facebook needs the JSON PHP extension.
    [string:private] =>
    [/code] => 0
    [file:protected] => /projects/p41/www/html/
    [line:protected] => 6
    [trace:private] => Array
    [0] => Array
    [file] => /projects/p41/www/html/
    [line] => 7
    [function] => include_once
    i dont have install json…..
    can i use xml instead of json….plz explain the way where i can use xml …in place of json_decode… that i need not to install json
    plz help

  • sanjay
    June 13, 2011 at 12:23 pm

    how we know , user has been cilick like button

  • manjesh
    June 15, 2011 at 11:24 pm

    I have developed some facebook apps using php sdk. I am usng similar code as u suggested in this article.

    But when user comes to my app very first time then after getting the required permission my apps are opening out side the facebook iframe.

    can u please suggest me… why its opening outside the facebook ifreame.

    • sanjay
      June 16, 2011 at 3:47 pm


      This is because Facebook loses all of the authentication variables and is unable to determine that the concurrent requests belong to the same session, which results in “breaking out” of the iframe and ending up on your own server pages instead of within Facebook.

    • sanjay
      June 16, 2011 at 3:49 pm

      In order to persist the session within your iframe app without breaking out to your server, you must include these parameters on each link’s query string. Here is a simple function that will produce the query string for you, so you simply need to append the result of this function to each link URL in your application:

  • manjesh
    June 15, 2011 at 11:26 pm

    //facebook application
    //set facebook application id, secret key and api key here

    $fbconfig['appid' ] = "xxxxxxxxxxxxxxxxx";
    $fbconfig['api' ] = "xxxxxxxxxxxxxxxxxx";
    $fbconfig['secret'] = "xxxxxxxxxxxxxxxxx";

    //set application urls here
    $fbconfig['baseUrl'] = ";;
    $fbconfig['appBaseUrl'] = ";;

    $uid = null; //facebook user id

    include_once "facebook.php";
    catch(Exception $o){
    echo '’;
    echo ”;
    // Create our Application instance.
    $facebook = new Facebook(array(
    ‘appId’ => $fbconfig[‘appid’],
    ‘secret’ => $fbconfig[‘secret’],
    ‘cookie’ => true,

    //Facebook Authentication part
    $session = $facebook->getSession();
    $loginUrl = $facebook->getLoginUrl(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘publish_stream’
    $fbme = null;

    if (!$session) {
    echo “top.location.href = ‘$loginUrl’;”;
    else {
    try {
    $uid = $facebook->getUser();
    $fbme = $facebook->api(‘/me’);

    } catch (FacebookApiException $e) {
    echo “top.location.href = ‘$loginUrl’;”;

    function d($d){
    echo ”;
    echo ”;

  • sanjay
    June 16, 2011 at 3:44 pm

    Facebook Apps and iFrames are installed on servers outside of Facebook and are ‘called in & displayed’ by Facebook when the user clicks on the application or iFrame.This information is generally NOT stored on servers with SSL Certificates, ie https, rather standard http servers, and so, as it is not considered ‘secure’ Facebook will NOT display the App/iFrame through the https connection.

    Facebook User (https) Facebook (https) … OK
    Facebook User (https) Facebook (https) App/iFrame (http) … NO!

    If the App/iFrame is stored on https servers …
    Facebook User (https) Facebook (https) App/iFrame (https) … OK

    If not the only way to access the App/iFrame is to switch back to the standard http connection, ie.”untick” the https secure browsing setting. has implemented a SSL Certificate on its iFrame servers and modifying all links to https, this will ensure that our iFrame Tabs work with both http & https connections.

  • sanjay
    June 25, 2011 at 1:26 pm

    how i know who like my application..?

  • rquotes
    July 20, 2011 at 2:04 am

    Looking for Love Quotes to woo your soulmate? Searching for sweet love sayings to reinforce a great romance? This is the place to be – is the hottest love quotes and romantic site on the net…..Enjoy…

  • Vestal watches
    August 10, 2011 at 6:07 pm

    Great share, I’m currently in process of creating something similar..

  • Anwaltsbüro Luzern
    August 14, 2011 at 11:32 pm

    This should be very helpful! Thanks.

  • Randhu
    August 24, 2011 at 9:28 pm


    I wonder if you can show pictures of the fans of my page, I found that I can display a list of pictures of my friends, but it would be like a page (fans) can?

  • Tom
    September 3, 2011 at 6:19 pm

    Is there any way to upload photos to a fan page through Graph API ?
    I am only able to upload to profile page.

    The main idea is to to give opportunity to upload photos to fanpage and display them.
    I was able only to show the photos for the album from the fanpage.

    I will appreciate Your help

  • canon5dreviews
    September 23, 2011 at 12:10 am

    We adore taking that approach. Thx 🙂

  • Tara
    November 3, 2011 at 3:35 am


    I have reviewed the Graph API docs online and did not find any guidance on how to pass in a line break as part of the message parameter. I tried \n, /n, but none of these work. Has anyone had success with this?


  • jigs
    April 3, 2012 at 1:35 pm

    This is the best article. Thanks..

  • jigs
    April 3, 2012 at 2:45 pm


    can we get data of

    using facebook php-sdk.?

    It is very imp for me.

    Let me know, if there is any way.

    Waiting for reply…

  • Cherise Holguin
    May 25, 2012 at 1:13 pm

    composed by sbsbsb0416 Great stuff from you, my friend. Ive read your posts before and you’re just Awesome! I love what you’ve got here, love what you’re saying and the way you say it. You make it entertaining and yet you still manage to keep it smart & to the point. I cant wait to read more from you. This is really a great & very well blog!