PHP SDK & Graph API base Facebook Connect Tutorial

facebookIn this article I’m focusing facebook latest php sdk to integrate facebook features in your site. Some days ago facebook released their new graph api system and updated their core structure. They also officially released php sdk so that you can easily call facebook latest graph api and old legacy api from server side by php.

Before proceeding first have a look my previous article specially Facebook connect authentication part.

In this post I’ll show

  1. How to check valid session of user, if user successfully logged in
  2. How to call graph api
  3. How to call legacy api
  4. How to update status dynamically using graph api
  5. How to use FQL Query

So take a look my demo of this tutorial. Please login by FBConnect and approve all the permission if you’re first time accessing the page.

Updated Tutorial

Follow this post based on PHP SDK 3.0 by Facebook and skip current post.

STEP 1:

First download the php sdk libary from here . Now copy the facebook.php from /src/ to your project dir.

STEP 2:

Create a file named fbmain.php. And copy below code to this file.

<?php
    $fbconfig['appid' ]  = "your application id";
    $fbconfig['api'   ]  = "your application api key";
    $fbconfig['secret']  = "your application secret key";

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

    // We may or may not have this data based on a $_GET or $_COOKIE based session.
    // If we get a session here, it means we found a correctly signed session using
    // the Application Secret only Facebook and the Application know. We dont know
    // if it is still valid until we make an API call using the session. A session
    // can become invalid if it has already expired (should not be getting the
    // session back in this case) or if the user logged out of Facebook.
    $session = $facebook->getSession();

    $fbme = null;
    // Session based graph API call.
    if ($session) {
      try {
        $uid = $facebook->getUser();
        $fbme = $facebook->api('/me');
      } catch (FacebookApiException $e) {
          d($e);
      }
    }

    function d($d){
        echo '<pre>';
        print_r($d);
        echo '</pre>';
    }
?>

First update $fbconfig array by your application’s id, api key and secret key. In the code you’ll see I included facebook.php by include_once. If your server has no curl extension and json extension, you’ll see error message. Until you don’t install curl and json extension this sdk will not work.

 $session = $facebook->getSession();

This method returns session information of user. It may be empty if user yet not logged in your site or user’s session is invalid. To check user’s session validity you’ve to first call an api, if user’s session is valid then the api will return result.

So if $fbme is not null that means user successfully logged in via facebook and user’s session is valid. So before calling any api use conditional logic like if ($fbme) { then call api}.

I also defined a method named d() to dump data quickly.

STEP 3:

Now create another file named index.php and copy below code and checkout my description at the end.

<?php
    include_once "fbmain.php";
    $config['baseurl']  =   "http://thinkdiff.net/demo/newfbconnect1/php/index.php";

    //if user is logged in and session is valid.
    if ($fbme){
        //Retriving movies those are user like using graph api
        try{
            $movies = $facebook->api('/me/movies');
        }
        catch(Exception $o){
            d($o);
        }

        //Calling users.getinfo legacy api call example
        try{
            $param  =   array(
                'method'  => 'users.getinfo',
                'uids'    => $fbme['id'],
                'fields'  => 'name,current_location,profile_url',
                'callback'=> ''
            );
            $userInfo   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }

        //update user's status using graph api
        if (isset($_POST['tt'])){
            try {
                $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> $_POST['tt'], 'cb' => ''));
            } catch (FacebookApiException $e) {
                d($e);
            }
        }

        //fql query example using legacy method call and passing parameter
        try{
            //get user id
            $uid    = $facebook->getUser();
            //or you can use $uid = $fbme['id'];

            $fql    =   "select name, hometown_location, sex, pic_square from user where uid=" . $uid;
            $param  =   array(
                'method'    => 'fql.query',
                'query'     => $fql,
                'callback'  => ''
            );
            $fqlResult   =   $facebook->api($param);
        }
        catch(Exception $o){
            d($o);
        }
    }
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>PHP SDK & Graph API base FBConnect Tutorial | Thinkdiff.net</title>
    </head>
<body>
    <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: '<?=$fbconfig['appid' ]?>', status: true, cookie: true, xfbml: true});

                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());

            function login(){
                document.location.href = "<?=$config['baseurl']?>";
            }
            function logout(){
                document.location.href = "<?=$config['baseurl']?>";
            }
</script>
<style type="text/css">
    .box{
        margin: 5px;
        border: 1px solid #60729b;
        padding: 5px;
        width: 500px;
        height: 200px;
        overflow:auto;
        background-color: #e6ebf8;
    }
</style>

    <h3>PHP SDK & Graph API base FBConnect Tutorial | Thinkdiff.net</h3>
    <?php if (!$fbme) { ?>
        You've to login using FB Login Button to see api calling result.
    <?php } ?>
    <p>
        <fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
    </p>

    <!-- all time check if user session is valid or not -->
    <?php if ($fbme){ ?>
    <table border="0" cellspacing="3" cellpadding="3">
        <tr>
            <td>
                <!-- Data retrived from user profile are shown here -->
                <div class="box">
                    <b>User Information using Graph API</b>
                    <?php d($fbme); ?>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>User likes these movies | using graph api</b>
                     <?php d($movies); ?>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="box">
                    <b>User Information by Calling Legacy API method "users.getinfo"</b>
                    <?php d($userInfo); ?>
                </div>
            </td>
            <td>
                <div class="box">
                    <b>FQL Query Example by calling Legacy API method "fql.query"</b>
                    <?php d($fqlResult); ?>
                </div>
            </td>
        </tr>
    </table>
    <div class="box">
        <form name="" action="<?=$config['baseurl']?>" method="post">
            <label for="tt">Status update using Graph API</label>
            <br />
            <textarea id="tt" name="tt" cols="50" rows="5">Write your status here and click 'submit'</textarea>
            <br />
            <input type="submit" value="Update My Status" />
        </form>
        <?php if (isset($statusUpdate)) { ?>
            <br />
            <b style="color: red">Status Updated Successfully! Status id is <?=$statusUpdate['id']?></b>
         <?php } ?>
    </div>
    <?php } ?>

    </body>
</html>

The code is very easy to understand. First part contains php logic, api call and collection of data. Next part is html/javascript to view data (javascript for fbconnect authentication).

Please change

$config['baseurl']  =   "http://thinkdiff.net/demo/newfbconnect1/php/index.php";

And set baseurl to your project url. And never forget to set your facebook application Connect URL. It would be your project url.

In index.php I used javascript based fbconnect authentication and fbml tag  to show login button and logout button. If you don’t want to use javascript for this purpose, you can generate login/logout links using php code.

Generate login/logout button using this php code

// login or logout url will be needed depending on current user state.
if ($fbme) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}

And show the generated links by below code

<?php if ($fbme) { ?>
    <a href="<?=$logoutUrl?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
    </a>
    <?php else: ?>
    <a href="<?=$loginUrl?>">
      <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
    </a>
    <?php } ?>

So user will see php generated login and logout button.

In the facebook.php sdk the getLoginUrl() function is defined as

/ * The parameters:
   * - next: the url to go to after a successful login
   * - cancel_url: the url to go to after the user cancels
   * - req_perms: comma separated list of requested extended perms
   * - display: can be "page" (default, full page) or "popup"
   *
   * @param Array $params provide custom parameters */
public function getLoginUrl($params=array()){....}

So if you want that your user approve additional permissions at the first time then generate the url by providing some parameters

 $loginUrl = $facebook->getLoginUrl(
     array('req_perms' => 'email,read_stream')
);

Now lets discuss more about api calling…

1. How to check valid session of user, if user successfully logged in

I already discussed it in the STEP 1. So I think you already have learned how to check valid session of user. Just remember to use if ($fbme) {call api}

2. How to call graph api

Its very simple. For http://graph.facebook.com/me  you’ve to use

 $fbme = $facebook->api('/me');


3. How to call legacy api

This is almost same as of graph api calling.

$param  =   array(
   'method'  => 'users.getinfo',
   'uids'       => $fbme['id'],
   'fields'     => 'name,current_location,profile_url',
   'callback'  => ''
);
$userInfo   =   $facebook->api($param);

So $facebook->api() is used to call both graph api and old legacy api. If you check the api() method in facebook.php sdk you’ll see

 public function api() {
    $args = func_get_args();
    if (is_array($args[0])) {
      return $this->_restserver($args[0]);
    } else {
      return call_user_func_array(array($this, '_graph'), $args);
    }
  }

That means if 1st argument is array then the api will call the old restserver.php  otherwise it will call the new graph server.

4. How to update status dynamically using graph api

try {
      $statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> 'sample status message', 'cb' => ''));
} catch (FacebookApiException $e) {
      d($e);
}

in facebook.php you’ll see

function _graph($path, $method='GET', $params=array()) {...}

So the first parameter is for graph path in here https://graph.facebook.com/me/feed, 2nd parameter defines HTTP post or get parameter and 3rd parameter defines array that contains necessary values. So ‘message’ is the message we want as status and ‘cb’ is the callback function which I set to null. Here http://developers.facebook.com/docs/api you’ll see all the information about graph api and their parameters, like

Method Description Arguments
/PROFILE_ID/feed write to the given profile’s feed/wall messagepicturelinkname,description

So to call any graph api just check the manual if you need to pass additional parameters or not.

Another example to retrieve user favorite movie names (https://graph.facebook.com/me/movies) use

$movies = $facebook->api('/me/movies');

5. How to use FQL Query

Currently I don’t find any way to call fql query using graph api. So use the technique of legacy api calling to run fql query

$fql    =   "select name, hometown_location, sex, pic_square from user where uid=xxxxxxxxxxxxxxx";
$param  =   array(
       'method'     => 'fql.query',
        'query'     => $fql,
      'callback'    => ''
);
$fqlResult   =   $facebook->api($param);

I hope this article will help you to understand the usage of php-sdk easily. Demo URL

:)

About mahmud ahsan

Programming is my passion from high school. I always looking for innovating new ideas and making them real application. I love mobile application and game development as well as web development. Having 4+ years web development experience and 6+ years mobile application development experience on different platform and business on it. My Mobile Apps Portfolio: iThinkdiff.net Mobile Apps

, , ,

296 Responses to PHP SDK & Graph API base Facebook Connect Tutorial

  1. marcos cabrera May 2, 2010 at 4:09 am #

    hi ,
    i reading your post and i like it.

    i have a lot of trouble with the new graph api, but i found this post.

    thx

  2. sertac May 2, 2010 at 5:22 am #

    impressive work again :)

  3. marcos cabrera May 2, 2010 at 2:41 pm #

    hi again!
    this evening i tested this code . works very well…….always and when this code is hosted out of facebook.
    so that i am rewriting the code for that works like a facebook app into a iframe…..

    In the road i had issues that i’ll try to solve soon …..when i finish i’ll post here.
    greetings!!!

  4. Ghido May 3, 2010 at 2:37 am #

    Good job again! What if I would like to develop an FBML application? There is no require_login method in this new SDK!

  5. mahmud ahsan May 3, 2010 at 2:47 am #

    @Ghido, I yet not tested fbml application. But I think the solution could be, if you don’t find user’s valid session then redirect user to the login url by the following code.

    if (!$fbme) {
      $loginUrl = $facebook->getLoginUrl();
    }
    
    if (isset($loginUrl)) {
        header("Location: $loginUrl);
        exit;
    }
    

    If you test this code let me know if it works or not.
    thank you.

    • Lionel Morrison May 28, 2010 at 11:09 pm #

      Awesome, this simple piece of code solved an issues where IE was not returning a session for a canvan app when the user is already logged in.

      Thanks

  6. James May 3, 2010 at 4:22 am #

    Is there a way to have a user click a link to update a facebook status and it then prompts them to allow permission? So example:

    They come to a site, enter a status in a text area, click “update status”. A pop-up appears and asks them to login if they aren’t already logged into facebook, and then asks for the appropriate permission. If they hit allow, it posts the status.

    Is that possible?

    Thanks so much for this great tutorial!

  7. Brian May 3, 2010 at 4:30 am #

    I LOVE YOU! Was having trouble figuring it out for a week. Everyday since, I was trying to find better examples. Finally, thanks.

  8. James May 3, 2010 at 4:30 am #

    Basically, logging in the user, letting them click “allow” and then posting the status. All with them clicking one button.

  9. James May 3, 2010 at 5:04 am #

    I got it figured out! Thanks for the tutorial!

  10. Njaka May 3, 2010 at 1:36 pm #

    I want to add new authorisation for my application. How to make a new Oauth authorisation request in php please.
    Thx

  11. agafex2 May 3, 2010 at 6:24 pm #

    @Ghido is rigth. Before it was posibble to obtain a facebook logued user id with require_login in a fbml application into facebook. Now i cant get that information without requering user relogin again.

  12. mahmud ahsan May 4, 2010 at 12:38 am #

    @Ghido and @agafex2, if you use iframe base application not fbml you can follow the guideline from facebook.

    http://developers.facebook.com/docs/guides/canvas/#canvas

  13. Mac Cullan May 4, 2010 at 12:48 am #

    Its very interesting that http://developers.facebook.com/docs/guides/canvas/#canvas in this site only iframe base canvas application discussed.

    It seems to me that, facebook will soon deprecate fbml base canvas application development. :(

  14. Emran Hasan May 4, 2010 at 3:57 am #

    @Ghido and others: I think I have found a workaround solution that works for IFrame based application. I have posted that on my blog here: http://bit.ly/cT40vV. Let me know if it works for you!

  15. alexl May 4, 2010 at 1:10 pm #

    instead of fql.query it only worked for me with facebook.fql.query

    param = array(
    ‘method’ => ‘fql.query’,
    ‘query’ => $fql,
    ‘callback’ => ”

  16. P-L Gendreau May 4, 2010 at 1:39 pm #

    Thank you! This is FAR better than Facebook’s own documentation

  17. yosi May 4, 2010 at 8:41 pm #

    Old rest api call aren’t working on the current release of PHP SDK – line 666 is true selecting the read only REST
    API which doesnt work – just change it to $name = ‘api'; as a fix!!
    theDigitalWarrior

  18. mahmud ahsan May 4, 2010 at 10:42 pm #

    Using the latest php-sdk many people facing problem regarding authentication for fbml/iframe base canvas application. Some of experts suggest me still to use old php sdk library. New php-sdk or new javascript sdk mostly suited for fbconnect base application.

  19. mahmud ahsan May 5, 2010 at 2:18 am #

    People, if you want to develop iframe base canvas application for facebook, then to know the how to use the authentication system don’t forget to visit http://bit.ly/cT40vV

    Thanks to Emran vai for his nice solution there.

  20. Rob May 5, 2010 at 5:02 pm #

    Hello. First of all this is a great tutorial thanks so much for it.

    Have you been able to successfully authenticate yourself on a subdomain using this code? I have tried but it doesn’t seem to work for me. I have included the base domain in the application settings.

    Anyone have any experience with this?

    Cheers
    rob.

  21. Rob May 5, 2010 at 7:29 pm #

    An update for you on this… It does work on sub domains it was the set up of my local development server that was causing the issue.

    Cheers
    Rob.

  22. Mile May 6, 2010 at 1:57 am #

    Thank you very much for this great tutorial.

  23. Derek Martin May 7, 2010 at 11:31 am #

    you rock! you made an intimidating subject easy to learn. facebook’s documentation is fantastic, BUT there’s too much of it, and no straightforward “start here” tutorial. thanks for yours :)

  24. Paul May 9, 2010 at 4:14 am #

    Hi,

    I have a problem.

    My test seems to keep on “refreshing” the page after login. This loops over and over.

    Any ideas?

    Thanks!

  25. Yaary Vidanpeled May 9, 2010 at 4:25 am #

    Hi there.

    For some reason I can’t seem to get $fbme to work

    I created new facebook application named dummytester

    put index.php fbmain.php and facebook.php

    changed $config[‘baseurl’] with index.php file

    changed these appropriatly @ fbmain.php file
    $fbconfig[‘appid’ ] = “”;
    $fbconfig[‘api’ ] = “”;
    $fbconfig[‘secret’] = “”;

    I get the login button and do get logged in. If i am allready logged in i get the “facebook logout” button.

    but i do not see the data that i am supposed to see if the php var $fbme was set to true.

    please help

  26. mahmud ahsan May 9, 2010 at 4:31 am #

    @Paul and @Yaary, read attentively the steps of this post.

    http://thinkdiff.net/demo/newfbconnect1/php/index.php The demo is working nicely (there is no looping problem and no getting no data problem) and I published the source code in this article. Many other programmers also successfully used this code. So I’ve no answers for you.

  27. Paul May 9, 2010 at 5:03 am #

    @Mahmud, you created a very clear and forward tutorial :)

    For some reason my code keeps on looping. Here is a link to it:

    http://mypaintballcircle.com/app/index.php

    Let me know if this loops from your computer.

    Not sure if there are some strange setting on the server that I am using to host the code.

    I will try to move this to a different server to test this.

    Thanks for commenting back :)

    Paul.

    • mahmud ahsan May 18, 2010 at 6:00 pm #

      hmm your one is redirecting again and again. I am not sure why its redirecting in your server. If you want to check everything from me, then you can give me the ftp access and make me developer access of the facebook application. Then I can take a look what is actually happening. If you want then mail me.

  28. Yaary Vidanpeled May 9, 2010 at 11:38 am #

    just for the reecord, the first time i tried the code, i attached the code to a preexisting facebook application and got the loop as well.

    I then went and changed migration settings and the looping stopped but in both cases, although I see a change in login logout button, no data

  29. paul May 9, 2010 at 9:21 pm #

    @Yaary, actually my facebook app is a pre-established app. I am going to scrap it and re-create it and see if that fixes the problem.

    @mahmud, I will try Yaary’s suggestion and if it fails, I will shoot you an email with credentails. Thanks for your help :)

  30. AJ May 11, 2010 at 6:10 pm #

    Hi Mahmud, I love the simplicity of tutorial and I’d have to agree with some of the others here that it’s more coherent and understandable than Facebook’s own documentation. Thank you so much for sharing your knowledge!

    Just a little contribution for your blog: for those who’re unable to get valid information into $fbme, a simple solution was posted on PHP-SDK github… you will need to add this line to facebook.php under the public static $CURL_OPTS array:

    CURLOPT_SSL_VERIFYPEER => false

    Apparently, there seems to be a problem with authenticating the SSL certificate, so this line should solve the problem. Once you add this line, there’s no need for the Javascript popup workaround (although, even that is wonderful l’il piece of work!)

    • Scotty October 22, 2010 at 1:22 am #

      Yes, thanks for the fix for that. If you’re $fbme is null, this will fix it.

  31. Yaary Vidanpeled May 11, 2010 at 6:32 pm #

    Thank You AJ

    after adding the fix to facebook.php, it works fine.

    And thank you Mahmud for a great tutorial.

  32. Fish May 12, 2010 at 3:39 am #

    Thanks for this post. It REALLY helped me out a lot.

    Question: If I wanted to have the user fill in a status update, but delay the submission of that status update for another time, is that possible with facebook? I am able to do this with Twitter by storing the oauth oauth_token and oauth_token_secret and use it later to call the twitter api. Is the same thing possible here?

    Thanks again!

    • mahmud ahsan May 12, 2010 at 1:06 pm #

      @Fish, yeah you can do this. You’ve to seek offline extended permission from user and status update permission. If user approves offline permission, store the session key in your database for that user. Then when you will create $facebook = new Facebook() object then assign the session using $facebook->setSession($usersession) code. And if user also approves status_update permission, you can now update user’s status behind the scene.

      • jukka June 21, 2010 at 4:49 am #

        Thank you of this

        About fish’s post
        what data comes to
        $facebook->setSession($usersession)
        to $usersession ?

        I have got a oauth-token that contains | and – signs (pipe and minus separating numbers and chars..)

  33. Jasman May 12, 2010 at 6:23 pm #

    nice share..
    can you give me an sample invitation using scripts sdk-php?
    thank you..

  34. Fish May 12, 2010 at 7:16 pm #

    @mahmud, Thanks so much. After playing around with it a bit more last night I came to realize thats how it works but have not implemented it yet. Do I save the entire session or just the “access_token”- Seems like I would save the full session, is that correct?

    Also, I am trying to figure out how to post to an authenticated users PAGE instead of their profile. In the past I believe we had to use “enable_profile_selector” but I’m not sure how to get the page choices.

    Thanks again!

    Fish

  35. Ernesto May 13, 2010 at 3:13 pm #

    Mahmud, congratulations for your posts. Are very interesting.

    I’m trying to make this thing work in a FB application using canvas and Iframe.
    No problem in chrome and mozzilla, but in Internet explorer 8 when the login pop up open there is an error “Page don’t load”

    http://apps.facebook.com/questionariouno/

    Whay i need to try is very simple:

    I only need some data (username and email) of the customer that logins in the application, and your example is the only one that “almost work”. The other I find simply doesn’t work at all.

    Any help?

    Thank you.

    • mahmud ahsan May 13, 2010 at 4:15 pm #

      @Ernesto, if you’re developing iframe base facebook app then follow my another tutorial: http://wp.me/pr3EW-sv I hope it will solve your problem.

  36. Feroze May 13, 2010 at 7:35 pm #

    How can i send gift from my application to selected users using Graph API. Please help with code…

  37. Pat May 14, 2010 at 10:25 pm #

    This is a great tutorial for the Graph API! One question though, how do I get information from the user for their work experiences? In the JSON tree it is some kind of subtree and I wasn’t sure how to get to it, or display it using the following:

    $userWork= $fbme[‘work’];

    That (obviously) doesn’t work. I can get all of their basic info, but not their work stuff and anything else that is hierarchical in nature. Any help would be great, thanks :)

  38. Pat May 14, 2010 at 10:43 pm #

    Thanks, much appreciated!!

  39. Yaary Vidanpeled May 14, 2010 at 10:49 pm #

    Hi to all

    I was wondering about the new Auth2.0 and the login button. I am trying to program a fbml based canvas application using flash as serverside.

    I am trying to get the auth popup window to open automatically if user has not logged on or if user has nor autherized the application yet.

    Any idea’s regarding what tools to use will be welcome

  40. Jason May 16, 2010 at 6:39 am #

    Brilliant – really useful. Been having some real problems implementing the Facebook Graph (mainly regarding auth/sessions), but this seems to have solved everything.
    Thanks!

  41. noor May 16, 2010 at 8:13 pm #

    @paul how did you solve your looping problem?
    I have same problem here

  42. MAADMAXX May 17, 2010 at 1:06 pm #

    Thanks for the timely article featuring Open Graph.

    A question though about using POST. I’m able to receive my user object, activities, statues, feed, posts etc, but my status does not update with this code, even when wrapped inside a if($session):

    $faceboook->api(‘/me/feed’, ‘post’, array(‘message’=> ‘sample status message’, ‘cb’ => ”));

    any thoughts? what am i missing? :)

    thanks,
    Ansdrew

    • mahmud ahsan May 18, 2010 at 5:58 pm #

      Are you kidding me? The demo nicely working for updating status. Check the demo and code.

  43. aleefus May 17, 2010 at 2:04 pm #

    Wow Nice! Good job…

  44. mwafi May 18, 2010 at 5:16 pm #

    can I retrieve list of my application’s users using graph api or fql?

  45. Gnanesh May 18, 2010 at 6:17 pm #

    Hi Mahmud,

    Another great post. Thanks a lot!
    I did everything that was asked.

    pdownloaded facebook.php, created fbmain and index.php

    But when i execute the index.php script, nothing comes up on the browser and I am getting the below error in my log file.

    Uncaught QueryParseException: An active access token must be used to query information about the current user.
    thrown in /home/wildfire/public_html/ignite/php/facebook.php on line 454

    Any idea how i can resolve this?

    Would appreciate your help greatly

    • Gnanesh May 20, 2010 at 2:42 pm #

      Figured it out.. Thanks anyways :)

      • faris madi July 28, 2010 at 4:30 pm #

        What was the solution? I’m getting the same error too

        • codefather November 29, 2010 at 5:43 am #

          also I do
          in spite of “stream.publish” method works well with this token

    • Michael Davis June 11, 2010 at 4:15 am #

      What was the solution? I’m getting the same error.

  46. buzzknow May 22, 2010 at 9:55 pm #

    hi Mahmud,

    why my page always refreshing after login/logout .. endless refreshing :(

    thanks

  47. Sweeta May 24, 2010 at 3:47 pm #

    This tutorial helped me a lot to move further with graph api. thanks

  48. Feroze May 24, 2010 at 9:26 pm #

    hi

    i’m using your code in my new application but me session remains always null even i’m logged in. Plz help… Also what is replacement of require_login() function. if a user does’nt add application he/she should show allow screen how can we reach this using new graph api… thanks in advance…

    • mahmud ahsan May 24, 2010 at 10:21 pm #

      Please read the article carefully, this article is for fbconnect base application. If you need help for iframe base canvas application development, please check all the comments, you’ll find another link about iframe application development.

  49. Arvi May 26, 2010 at 12:56 pm #

    Thanks for this article! It helped me so much. You give me a break..Thanks!

    I just have some questions ^^ I was playing with the parameters using the PHP SDK and when I use “popup” as my display, it still takes up the whole page but the layout was moved to the left. It didn’t pop up. I don’t know what’s missing or what’s wrong.

    Also, how can I set show-faces=true as a parameter(Login Faces Social Plugin). I don’t know if this is already possible in PHP SDK, there is no mentioned parameter in the source. In javascript it’s this
    , but I want to implement it in PHP

    I’m thinking right now, it can only handle extended permissions(req_perms).

    Thanks again!

    • Arvi May 26, 2010 at 1:33 pm #

      Ahaha I found your article about the popup…should’ve browse first before asking. Sorry, I’m just excited! You make it look so easy…better than Facebook API documentation ^^ Thanks!

  50. Jenry May 27, 2010 at 6:52 am #

    I have read ALL the facebook.php code and then I found this, damn :(
    GREAT WORK mahmud ahsan !!!

  51. Sahaza May 28, 2010 at 6:34 pm #

    Mahmud thank you you’re the best ;)
    but I have a problem trying to display my feeds by calling $ facebook-> api (‘/ me / feed’);
    nothing appears :( how do I do to show my last 10 status?
    thank you in advance

  52. srinivas May 28, 2010 at 7:18 pm #
    Hi I am trying to develop an application, which i can run in facebook. Like which i can add to my user or page.

    But i am having a basic problem.

    i am getting the login url using getLoginUrl()
    but when i am redirecting to that url, i am getting some different issues for different browsers.

    my application is http://apps.facebook.com/helloworld_udvh/

    issues i am getting..

    =================================================================
    Issue in IE7 Browser
    =================================================================
    There is a problem with this website’s security certificate.

    The security certificate presented by this website was issued for a different website’s address.

    Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.
    We recommend that you close this webpage and do not continue to this website.
    Click here to close this webpage.
    Continue to this website (not recommended).
    More information

    If you arrived at this page by clicking a link, check the website address in the address bar to be sure that it is the address you

    were expecting.
    When going to a website with an address such as https://example.com, try adding the ‘www’ to the address,

    https://www.example.com.
    If you choose to ignore this error and continue, do not enter private information into the website.

    For more information, see “Certificate Errors” in Internet Explorer Help.

    =================================================================
    Issue in Google Chrom Browser
    =================================================================
    This is probably not the site you are looking for!
    You attempted to reach http://www.facebook.com, but instead you actually reached a server identifying itself as a248.e.akamai.net. This

    may be caused by a misconfiguration on the server or by something more serious. An attacker on your network could be trying to

    get you to visit a fake (and potentially harmful) version of http://www.facebook.com. You should not proceed.

    =================================================================
    Issue in Fire Fox Browser
    =================================================================
    Secure Connection Failed
    http://www.facebook.com uses an invalid security certificate.

    The certificate is only valid for the following names:
    a248.e.akamai.net , *.akamaihd.net

    (Error code: ssl_error_bad_cert_domain)
    * This could be a problem with the server’s configuration, or it could be someone trying to impersonate the server.

    * If you have connected to this server successfully in the past, the error may be temporary, and you can try again later.

    Or you can add an exception…

    ===========================
    code i used:
    ===========================

    <?php
    
    require '../../libs/facebook.php';
    define("FACEBOOK_APP_ID", '');
    define("FACEBOOK_API_KEY", '');
    define("FACEBOOK_SECRET_KEY", 'MYAPPSECRETKEY');
    define("FACEBOOK_CANVAS_URL", 'http://apps.facebook.com/helloworld_udvh/');
    
    $facebook = new Facebook(array(
        'appId'  => FACEBOOK_API_KEY,
        'secret' => FACEBOOK_SECRET_KEY,
        'cookie' => true,
        'domain' => 'udbhavah.com'
    ));
     
    $session = $facebook->getSession();
     
    if (!$session) {
     
        $url = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect' => 0));
        //echo $url;
       echo "top.location.href = '$url';"; 
    } else {
        try {
     
            $uid = $facebook->getUser();
            $me = $facebook->api('/me');
     
            $updated = date("l, F j, Y", strtotime($me['updated_time']));
     
            echo "Hello " . $me['name'] . "";
            echo "You last updated your profile on " . $updated;
     
        } catch (FacebookApiException $e) {
     
            echo "Error:" . print_r($e, true);
     
        }
    }
    
    ?>
    

    please help me on this.

    thanks in advance.
    srinivas p.

  53. srinivas May 28, 2010 at 10:13 pm #

    Hi mahmud,

    thanks for your prompt response.

    even i am not facing the issue for my app
    http://apps.facebook.com/helloworld_udvh

    when i am trying after my laptop is connected to VPN.

    Without VPN connection i am getting this error.

    Can you pl. help on this..

    thanks in advance,
    srinivas P.

  54. Frank May 29, 2010 at 4:35 am #

    This demo really helped me out in regards to formatting things nicely and understanding what was going on a bit better. Does anyone know of good examples/tutorials on formatting the returned graph array data in CSS?

  55. supanat May 29, 2010 at 10:20 pm #

    I am very newbie to facebook’s programming.
    I tried to follow a step by step
    I found this error “Facebook needs the JSON PHP extension” when I run the application.

    Do I miss some files to run the apps?
    Can you please help me how to solve the problem?

    Thanks.

    • mahmud ahsan May 30, 2010 at 12:23 am #

      In your server you must have to installed json php extension. Please search in google before asking any question. You’ll find 99% answer in google. Thanks

  56. Christopher Gaston May 30, 2010 at 12:53 pm #

    Do you have any idea how to integrate this with WordPress?

    I am able to use this in the header section of my wordpress site, but somehow the $session, $uid, $fbme variables are lost or cleared in other sections.

    In my comment section, I call if($fbme) and it returns null. Though from my header, it shows I am logged in.

    Thanks for the article and any help!
    christopher

  57. ALSOFT May 31, 2010 at 2:36 pm #

    very good work

  58. kowach June 2, 2010 at 1:49 am #

    Is there way to get users real email? Requesting email parm (‘req_perms’ => ‘email’) I get only user facebook proxy mail.

  59. Daniel June 2, 2010 at 4:29 pm #

    Hi! great tutorial.

    I can’t seem to get $session even if I’m logged in and authenticated. It’s just null. The FB javascript indicates that I’m logged in.

    • Daniel June 2, 2010 at 4:33 pm #

      UPDATE: It works when I try your demo. But on my site I get no session and thus no data.

      I’m running my site on localhost btw, and that’s what I’ve put in the app settings. I now for a fact that authentication works because it works with the JS SDK, but I want to use the PHP SDK.

      • Josh June 3, 2010 at 7:23 am #

        I’m having the exact same problem, except i’m not running on localhost, just directly accessing the site through IP.

        I can’t get a valid session… any help?

        • DE June 5, 2010 at 6:27 am #

          Make sure your curl and json extensions are installed and enabled. Also, make sure you have SSL CA certificates installed (type: sudo apt-get install ca-certificates). This should cure your problem. Good luck!

  60. Nitish June 5, 2010 at 6:11 pm #

    Thanks Man , U are the Best , Excellent Article, Its working perfectly.
    Can u plz also tell me how can i do the wall posting frm Graph API.

  61. MJ June 6, 2010 at 2:34 am #

    Excellent tutorial – Thank you for taking the time to post this!

  62. Gil June 6, 2010 at 6:31 am #

    Thanks for the tutorial!
    I only don’t know and understand how to custom the output content.
    Right now I’m getting all the content into an array as:
    Array
    (
    [id] => 123456789
    [name] => Gil
    )

    But I don’t want it to be in array
    how can I custom the output please?
    For example I want something like this:
    $user[‘id’]
    $user[‘name’]

  63. César June 7, 2010 at 9:11 pm #

    Hi, im trying to set up what you described. I’m getting problems. When I run it on my server i get the same but without de button. Don’t no if i’m doing something bad o what. I’ve xampp latest version and curl, json on.

    Can you send me via mail, the files, Index.php, fbmain.php

    Thanks a lot. My boss is going to killme if I don’t connect this soon.

  64. Dani June 8, 2010 at 12:53 am #

    Hi Mahmud,
    thanks for your great tutorial!
    I’m having troubles when I put this code onto my server, I’m getting a timeout error and I don’t understand why. Maybe you have a clue about what is happening.
    That’s what I get:

    [result:protected] => Array
            (
                [error_code] => 6
                [error] => Array
                    (
                        [message] => name lookup timed out
                        [type] => CurlException
                    )
    
            )
    
        [message:protected] => name lookup timed out
        [string:private] => 
        [code language=":protected"][/code][/code] => 6
        [file:protected] => /var/www/vhosts/xxxx.com/httpdocs/php/facebook.php
        [line:protected] => 513
        [trace:private] => Array
    

    Thank you!

    • james June 16, 2010 at 9:01 pm #

      Hi Dani,

      i’m also having the same problem.
      curl on “api-read.facebook.com” always return name lookup time out.. its frustrating :(
      Have you found any solution?

      thank you.

      best regards,
      James

      • dan June 21, 2010 at 1:59 am #

        same problem here…..
        does anyone knows the answer?

        • Green July 1, 2010 at 3:31 am #

          Hi, Same problem here too!
          I get a time out error, then later my app starts working again!

          It only happens during the day….

          What should I do to determine the problem?

        • Green July 1, 2010 at 3:36 am #

          This post on the FB DEV API FORUM has some interesting information:

          http://wiki.developers.facebook.com/index.php/Talk:Users.getInfo

          It talks about the nameserver timeout. I think Facebook’s DNS Servers are having a problem…

      • Green July 2, 2010 at 4:34 am #

        I think i’ve figured it out.
        Adjust the CURL timeout settings in the facebook.php

        Find this var and adjust to increase the connection Time Out.
        CURLOPT_CONNECTTIMEOUT => 30

        This is my site, where I’m trying to start a forum about
        facebook application development. I’d really like some support if anyone’s willing to give some, I’ll share more of what I know!

        http://green.cx (Forums link is at the top of the page)

  65. Binay Kumar Shaw June 11, 2010 at 3:03 am #

    Thank you so much for your great tutorial.
    Let me know how can i get email id of the users who were logged into my site using facebook id. This because of my database maintenance of my project that who were logged into my site by using their facebook email id and password.

    By the whole i can i got the email id of user who were logged into my site.

    • mahmud ahsan June 11, 2010 at 4:22 pm #

      Just provide the email extended permission as my example, then using fql query you can retrieve his email address easily. You can also check the example http://thinkdiff.net/demo/newfbconnect1/php/index.php and look User Information using Graph API this part. You will see your facebook email there. So read the code and use it in your site. thanks.

      • nidhi July 31, 2010 at 6:11 pm #

        hi
        ur application is great..
        i have some problem ,i.e.
        i want to login in facebook without using fb:login button..

        Is it possible to allow a user to enter username and password to a Facebook account in a 3rd party application (outside of the Facebook system), and then submit it to the Facebook API to get access?
        please reply…
        thanks

      • nidhi August 5, 2010 at 1:52 pm #

        please reply….any thing u know about it…

  66. raja June 11, 2010 at 5:39 pm #

    Thank you so much for your great tutorial.

    i am having one problem by using facepile to my project.

    i am getting below error when i click facepile

    “The Facebook Connect cross-domain receiver URL (http://static.ak.fbcdn.net/connect/xd_proxy.php#?=&cb=f34e18026c4e01&origin=http%3A%2F%2Fwww.promolife.com.au%2Ff2f0bf484991814&relation=parent.parent&transport=postmessage) must have the application’s Connect URL (http://promolife.com.au/) as a prefix. You can configure the Connect URL in the Application Settings Editor.

    why do i get this error . how can use facepile in php

    • Sridhar Devulkar June 25, 2010 at 4:10 am #

      Raja, you get this error because the Connect URL in the application settings in facebook is empty. You can provide the same canvas url for the connect url and it should work fine. Try it out.

      Sri.

  67. trojan June 20, 2010 at 3:15 am #

    thanks, good tutorial
    It was of great help

  68. Sakvith June 27, 2010 at 2:28 pm #

    Hello mahmud,

    I follow you JS sdk tutorial and it worked fine.
    But now when doin the php sdk no luck.

    the page always return empty.

    I use js-sdk to login and hope to use php for fetch data.
    and i don’t promt errors (ie: curl and json). Just blank.
    please help.??

    • Sakvith June 28, 2010 at 12:33 am #

      Found the error. appId is not workd php to javascript.
      hardcode the appId. the it works..

      thanx. great tutorial.

  69. Mohd Ridzwan June 28, 2010 at 12:38 am #

    Assalamu’alaikum Mahmud. Thank you for a very good tutorial.

    But I have one request, can you teeach us how to upgrade current WordPress plugin that using old Facebook platform to use this new Graph API?

    I’m currently using the WP-FB-AutoConnect plugin, but the creator of this plugin seems kinda busy to upgrade it.

    Help from other also appreciated. Thanks.

  70. rhio June 30, 2010 at 6:28 am #

    hallo mr mahmud n all….

    i have error “Protocol https not supported or disabled in libcurl in facebook connect”

    how to solve the problem??
    plz help me…

    Libcurl in my hosting Enable.

  71. Mrudul July 2, 2010 at 1:30 pm #

    dear Mr. Mahmud ,
    This is what all I have done….
    but can you provide me the example use of the function users.getStandardInfo

    it would be great help to me…….

  72. Robin July 6, 2010 at 9:05 pm #

    Thanks for this fantastic post!

    I spent days looking for a good way to update a users facebook status through PHP. This explains it!

    Thanks!

  73. mrmuggles July 7, 2010 at 10:21 am #

    Thanks, great tutorial. It helped me a lot. With all the different methods on how to connect on FB available, it can be hard to figure it out!

  74. Noah July 7, 2010 at 10:23 pm #

    Great article!

    Just one question about security in general. How can I restrict direct download of my php files from people that want to look at my script code? I don’t want people looking into my index.php file!

    Please let me know how/if this is possible.

    Kind regards,

    Noah.

  75. Arvi July 12, 2010 at 6:43 pm #

    Is it also possible to set a parameter for Login to turn into Login with Faces in PHP SDK? Thanks :D

  76. Khalid July 13, 2010 at 5:43 pm #

    Hi Mahmud,

    Thanks again for this useful tutorial, I just got a question, how do i get the id of the last uploaded image?

    I try this:

    SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner=’100001106637062′ ) ORDER BY created DESC LIMIT 1

    but it returns this : “pid”: “100001106637062_111810″
    which is the user_id followed by the image id. not sure how to separate them My ultimate goal is to redirect user to the last image uploaded on his/her account. Please help,

    Thanks
    Khalid

    • mahmud ahsan July 13, 2010 at 11:49 pm #

      This question isn’t related with this article.

  77. Manish July 14, 2010 at 9:14 pm #

    Hi Mr. Mahmud ahsan,
    really gr8 work man..
    ..
    I face err while running below code :
    =============================

    hello
    Exception is CurlException: 6: name lookup timed out

    <?php
    session_start();
    require_once 'src/facebook.php';
    require_once 'config.php';
    $fbid= $_REQUEST["fb_sig_user"];
    $logo= $_REQUEST["imgname"];
    echo "hello “;
    try
    {
    $fql = “SELECT name, pic_big FROM user WHERE uid=’$fbid'”;
    $param = array(‘method’ => ‘fql.query’,’query’ => $fql,’callback’ => ”);
    $fqlResult = $facebook->api($param);
    }
    catch (FacebookApiException $e)
    {
    echo “Exception is “.$e;
    }
    print_r($fqlResult);
    ?>
    ==========================
    If possible please look into it..

    Thanks in advance. :)

    • mahmud ahsan July 15, 2010 at 1:43 pm #

      I’m not facing such type of error in my applications. So no idea.

    • Maz August 16, 2010 at 2:51 pm #

      Hi Manish,

      $param = array(‘method’ => ‘fql.query’,'query’ => $fql,’callback’ => ”);
      $fqlResult = $facebook->api($param);
      

      change it to new graph api call,

      $_friends = json_decode(file_get_contents("https://api.facebook.com/method/fql.query?query=".urlencode($fql)."&access_token=".$facebook->getAccessToken()."&format=json"));
      
  78. Manish July 15, 2010 at 1:46 pm #

    hello sir,
    In sort unable to execute fql properly.

    $fql = “SELECT name, pic_big FROM user WHERE uid=’$fbid’”;
    $param = array(‘method’ => ‘fql.query’,’query’ => $fql,’callback’ => ”);
    $fqlResult = $facebook->api($param);

    =========================
    out put is :
    Exception is CurlException: 6: name lookup timed out

    Sir any idea ??

      • Manish July 15, 2010 at 7:12 pm #

        there are no any solution..

        if u have any idea how to execute query with new api .. pls let me know.
        It would be gr8 help
        Thanks in advance..

        • mahmud ahsan July 16, 2010 at 1:45 am #

          Below code works in my application. So i don’t know why its not working in your case.

          //fql query example using legacy method call and passing parameter
                  try{
                      //get user id
                      $uid    = $facebook->getUser();
                      //or you can use $uid = $fbme['id'];
          
                      $fql    =   "select name, hometown_location, sex, pic_square from user where uid=" . $uid;
                      $param  =   array(
                          'method'    => 'fql.query',
                          'query'     => $fql,
                          'callback'  => ''
                      );
                      $fqlResult   =   $facebook->api($param);
                  }
                  catch(Exception $o){
                      d($o);
                  }
          
          
  79. Saiful Amri July 15, 2010 at 8:47 pm #

    great article, thanks, btw @srinivas : hello Mr. Srinivas, how are you?

  80. Saiful Amri July 16, 2010 at 12:48 am #

    Dear Mr. Mahmud….
    how to add action link on a wall…

    I have tried like this

    $fbme = $facebook->api(‘/me’);
    $attachment = array(‘message’ => ‘hello’,
    ‘name’ => ‘hello 2′, ‘caption’ =>’hello caption’ ,
    ‘link’ => ‘link hello’,
    ‘description’ => ‘nothing’,
    ‘picture’ => ‘http://example.com/pic.jpg’,
    ‘actions’ => array(array(‘name’ =>’ this action’,
    ‘link’ => ‘http://example.com’) );

    thanks for your hands…

    • mahmud ahsan July 16, 2010 at 1:34 am #

      action links should be json encoded.

      function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
          FB.ui(
          {
              method: 'stream.publish',
              message: '',
              attachment: {
                  name: name,
                  caption: '',
                  description: (description),
                  href: hrefLink
              },
              action_links: [
      	        {
      	            text: hrefTitle,
      	            href: hrefLink
      	        }
              ],
              user_prompt_message: userPrompt
          },
          function(response) {
          });
      }
      
  81. shanavas July 16, 2010 at 11:26 am #

    Hi Mahmud Ahsan,
    I have gone through ur nice post, started implementing it, unfortunately from the 2nd step itself, i had error
    I am getting null value for the $facebook->getSession(); even if i login to the facebook.
    please let me know how it is happening.

    I search in google but i fund some complected step
    http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/
    I have to go through this steps??

    What is my need is, I will be having some face book id in my table. we i clicked a button from my facebook. I need to publish wall to all this id. Please let me know whether is possible or not?
    waiting for ur valuable information
    with regards
    Shanavas

  82. Saiful Amri July 16, 2010 at 3:39 pm #

    Thanks Mr. Mahmud…

    I want to do adding action_links using php? thanks you share using javascript..

    Is there any code using php?

    • mahmud ahsan July 16, 2010 at 10:18 pm #
      try {
          $actions                =   json_encode(array(array('text'=>'Click Here', 'href'=>'http://thinkdiff.net')));
          
          $param  =   array(
                  'method'        =>  'stream.publish',
                  'callback'      =>  '',
                  'message'       =>  $msg,
                  'attachment'    =>  '',
                  'action_links'  =>  $actions,
                  'target_id'     =>  '',
                  'uid'           =>  '',
                  'privacy'       =>  ''
          );
          $result   =   $facebook->api($param);
      }
      catch(Exception $o) {
      }
      
      • Justn Cribb July 19, 2010 at 10:44 am #

        I have followed the same thing but I can’t seem to get it to work.

        $facebook = new Facebook(array( 'appId' => $app_id,
        'secret' => $secret,
        'cookie' => true, ));
        
        $msg = “hello”;
        
        try {
        $actions = json_encode(array(array('text'=>'Click Here', 'href'=>'http://thinkdiff.net')));
        
        $param = array('method' => 'stream.publish',
        'callback' => ”,
        ‘message’ => $msg,
        ‘attachment’ => ”,
        ‘action_links’ => $actions,
        ‘target_id’ => ”,
        ‘uid’ => ”,
        ‘privacy’ => ”
        );
        $result = $facebook->api($param);
        }catch(Exception $o) {}
        

        Please never mind the quotes, it’s not displaying properly here hehe. Thanks for any suggestions.

  83. Saiful Amri July 16, 2010 at 7:09 pm #

    Dear Mr. Mahmud…

    do you know how to fix it, if I update status like this “I can’t wait” the wall of facebook display “I can't wait” , thanks for your hands…

    Best Regards,

    Saiful Amri (Dagohill Founder)

  84. Saiful Amri July 16, 2010 at 10:29 pm #

    thanks Mr. Mahmud….

    the last my question is how to fixed problem about special character

    thanks for your all hands…

    Best Regards…

    Saiful Amri

  85. Saiful Amri July 16, 2010 at 11:58 pm #

    Great!!! @mahmud ahsan says on July 16, 2010 at 10:18 pm

    It’s worked 100%

    Thanks

    • Justn Cribb July 19, 2010 at 10:08 am #

      Hello Saiful! I just like to ask how do you get it to work? I can’t get it to work. If you can help me figure out what am I missing here:
      Thank you!

      • Saiful Amri July 19, 2010 at 2:06 pm #

        Hello Patrick…

        The first, is your application using latest facebook.php ?

        then before execute the code above have you check your SESSION ?
        example :

        $session = $facebook->getSession();
        $uid = $facebook->getUser();
        				   
        $fbme = null;  
        if ($session) {
        //put the code here...
        } 
        

        Thanks, I hope it can help you…

        • Saiful Amri July 19, 2010 at 2:10 pm #

          I am sorry I mean for Justn Cribb, :D, but it’s for at all too…

          btw…

          Justn Cribb, I used the code for publish stream only and not for update update status…

          thanks

          • Justn Cribb July 19, 2010 at 2:50 pm #

            Yep. I am trying to convert my Post action(which is working) to Publish Stream so I can have action links.

            $post = $facebook->api(‘/me/feed?access_token=’.$this->facebook_oauth_token, ‘post’,
            array(‘message’=> $message, ‘name’ => $name, ‘link’ => $link, ‘caption’ => $caption, ‘description’ => $description,
            ‘picture’ => $picture));

            I’m curious, why is there no access_token param for publish_stream? I tried adding it, but it doesn’t work. Did you just do that getSession and followed Mahmud’s code…like copy-pasted it to test and it worked already? Or did you have some tweaks?

            By the way, thanks for replying Saiful. I appreciate it a lot. I’m kinda stuck haha!

        • Saiful Amri July 19, 2010 at 3:59 pm #

          hello Justn Cribb,

          yes, the first I just copy and paste code from Mr. Mahmud (thank you so much) and then I try and it works, actions_links is displayed, for update status does not need action_links, or attachment, action_links is just for Publishing a Post Containing an Image, Action Link, and Custom Metadata or Publishing a Post Containing Flash, Action Link, and a Target.

          access_token param is saved in session or cookies…

          does your 2nd code above is for update status?

          example for update status I should use like below :

          //facebook status update
          // Create our Application instance.
          $facebook = new Facebook(array(
          		  'appId'  => $fb_appid,
          		  'secret' => $fb_secret',
          		  'cookie' => true,
          		));
          
          $session = $facebook->getSession();
          $uid = $facebook->getUser();
          $fbme = null;  
          if ($session) {  
          	$fbme = $facebook->api('/me'); 
          	try {
          	$statusUpdate = $facebook->api('/me/feed', 'POST', 
          		    array('message'=>$msg, 'cb' => ''));
          			} catch (FacebookApiException $e) {
          				//d($e);
          			} 
          //end facebook status update
          
          
          ///for stream publish I should use like  below:
          
          actions =   json_encode(array(array('text'=>'Dagohill', 'href'=>'http://dagohill.com')));
          
          //facebook stream publish
          // Create our Application instance.
          										$facebook = new Facebook(array('appId'  => $fb_appid, 'secret' =>$fb_secret,'cookie' => true,));
          
          $session = $facebook->getSession();
          $uid = $facebook->getUser();						$fbme = null;  
          if ($session) {  
          	try {
          $message = " just leave a news "; 
          $attachment = array( 'name' => $title, 'href' =>$href, 'caption' =>' rated it 5 stars', 'description' =>$summary, 
          'properties' => array('category' => array( 'text' => 'news', 
          		'href' =>$href2), 'ratings' => '5 stars'), 
          		'media' => array(array('type' => 'image', 'src' =>$imageurl, 'href' =>$href)),'latitude' =>$latitude, 
          //Let's add some custom metadata in the form of key/value pairs 
          'longitude' => $longitude);
          $attachment = json_encode($attachment); 
          
          $param  =   array('method'        =>  'stream.publish',
          					              'callback'      =>  '',
          							'message'       =>$message, 'attachment'    =>  $attachment , 'action_links'  =>  $actions,
          'target_id'     =>  '', 'uid'           =>  '',
          'privacy'       =>  ''
          );
          
          $result   =   $facebook->api($param);
          }catch(Exception $o) {
          //
          }
          
          //end facebook stream publish
          

          I hope it can help you….

          thanks

          • Justn Cribb August 19, 2010 at 7:09 am #

            Hello Saiful! I’ve been pretty occupied lately, but I just dropped by to thank you…your solution worked! Thanks for sharing your knowledge ^^

          • Joe August 25, 2010 at 12:26 am #

            Saiful,

            Could you please the same functionality with javascript sdk

            Thanks,
            Joe

          • Joe August 25, 2010 at 12:28 am #

            I mean provide the same functionality with Javascript sdk

  86. patrick July 17, 2010 at 3:05 am #

    first off, i want to say “thank you” for this great tutorial; i’ve been wrestling with this all week and yours is the first i’ve come across to make real sense and actually work.

    however, there’s a small error here that i needed to fix to get this code to work:

    in the form that submits a post to the wall, there is a line that reads:
    action=””

    i had to change this to the following for it to post properly:
    action=””

    i also had to adjust the permissions, which you touched on in tutorial.

    i hope that this is helpful; this is a great reference and i just want to make sure it works! thanks again!

  87. patrick July 17, 2010 at 3:07 am #

    my above comment didn’t format correctly, it did not display the code parts! let me try again:

    in the form that submits a post to the wall, there is a line that reads:
    action=”\”

    i had to change this to the following for it to post properly:
    action=”\”

    i hope this displays correctly…

    • patrick July 17, 2010 at 3:10 am #

      trying again…. screw it, i’m taking out the carrot marks; i hope you guys can figure out what i’m talking about:

      in the form that submits a post to the wall, there is a line that reads:
      ?=$config[‘baseurl’]?

      i had to change this to the following for it to post properly:
      ?php echo $config[‘baseurl’]?

  88. ben July 22, 2010 at 1:26 am #

    this tutorial is really good
    but i find the demo does not works well

    $session=$facebook->getSession();

    DO $session get value by GET?

    is there any method to get $session by POST or other way

  89. Raju July 22, 2010 at 6:12 pm #

    Can you pls post the code snippet in PHP, for posting comments to logged in user wall using graph API thru CURL.
    I could not really figured out doing this.

  90. vincy July 24, 2010 at 3:54 pm #

    really good!!
    Can you tell me how I can take all user id of my facebook application (by fql)??

  91. Amine CHAFAI July 26, 2010 at 8:05 pm #

    Thank you Mr. Mahmud for this tutorial… it helps me a lot to understand how the new facebook API works.

  92. magnetik July 27, 2010 at 4:50 am #

    Is it possible to check what permissions the auth_token has (with latest php sdk and opengraph)?

    • Michael Herrick September 2, 2010 at 12:08 am #

      I also would love to know the answer to this.

  93. judef July 29, 2010 at 7:55 pm #

    I love this tutorial, saved my time…Good work mahmud ahsan

  94. bed August 1, 2010 at 10:33 pm #

    Hi, gr8 tutorial.
    How i can get all events that i’v created and shared on my wall?

    Thanks in advance. :-)

    • nidhi August 2, 2010 at 1:19 pm #

      there is event class in Facebook API,by which u can fetch and create events from ur application

  95. mscherzer August 2, 2010 at 3:53 pm #

    Hi,
    For those using coldfusion, i have ported the facebook php-sdk to cfml.

    cheers

    marcel.

  96. bed August 2, 2010 at 4:33 pm #

    @nidhi: is in facebook.php ?
    How i can instantiate de event class?

    • nidhi August 2, 2010 at 5:06 pm #

      I m working on c#
      and using latest version of facebook api.
      and i dont think that is there any difference in c# and php api.
      i used following code which is in c#
      System.Collections.Generic.IList events = api.Events.Get();
      convert it into php.

  97. anant August 2, 2010 at 5:08 pm #

    hi,
    i am trying to post the comment on facebook status,
    can any1 help me by using the same api
    try {
    $statusUpdate = $facebook->api(‘/me/feed’, ‘POST’,
    array(‘comments’=>$comment, ‘cb’ => ”));
    } catch (FacebookApiException $e) {
    //d($e);
    }

  98. anant August 2, 2010 at 5:21 pm #

    HOW TO ADD COMMENT ON PARTICULAR STUTAS ??????????//

    Plsssssssss……………,, can any1 help??????????

  99. bed August 2, 2010 at 5:27 pm #

    ok nidhi i try;)

  100. nidhi August 2, 2010 at 8:31 pm #

    hi
    ur application is great..
    i have some problem ,i.e.
    i want to login in facebook without using fb:login button..

    Is it possible to allow a user to enter username and password to a Facebook account in a 3rd party application (outside of the Facebook system), and then submit it to the Facebook API to get access?
    please reply…
    thanks

  101. Kirk Elliott August 4, 2010 at 9:03 pm #

    “Until you don’t install curl and json extension this sdk will not work.”

  102. Fred Zhou August 5, 2010 at 1:36 pm #

    How to add application in Facebook page?

  103. Manish August 6, 2010 at 7:26 pm #

    hello sir,
    one quick question can we display like button in gaph api without JS and iframe..
    Thanks in advance for your kind reply.

  104. saravanan August 7, 2010 at 10:43 am #

    hi,

    do you have any detail about how to incorporate the login feature of facebook using ONLY PHP and not FBML and stuff so that user can login and allow him to post via PHP from mysite.

    if so kindly let me know.

  105. Sav August 10, 2010 at 12:50 am #

    Urgent.. I have got a problem trying to follow your step. After prompted login and was logged in, it will have the FacebookApiException Object showing that Protocol https not supported or disabled in libcurl and the type is CurlException.

    How am I able to solve this problem ?

    • Sav August 13, 2010 at 12:14 am #

      Im hosting on site11.

      My application site is http://fbposting.site11.com/, btw do any free website hosting support http and libcurl ?

  106. Andrew August 12, 2010 at 10:25 pm #

    Thanks for the good article.
    I need two helps:
    (a) how can I change the button name text “Facebook Logout” to Facebook & My Siste Logout”.

    (b) How can I call the php function to do the Facebook Logout uisng php? Because I need to execute the Facebook Logout, when someone removed their account.

  107. Dineshkumar August 14, 2010 at 12:16 pm #

    Dear Mr.Mohamad,

    I am beginner to Facebook Application.I taken your sample and execute it.All Works except Update Status.Returns the follwing error,
    [error] => Array
    (
    [type] => Exception
    [message] => (#200) The user hasn’t authorized the application to perform this action
    )

    Please help me to fix this…
    Thanks in Advance
    DineshKumar

  108. vadim August 19, 2010 at 2:54 am #

    thank you for great tutor. i think i followed all steps ,but i get error when i go to the application page :

    Parse error: syntax error, unexpected T_INCLUDE_ONCE in /home5/xxxxxxx/public_html/connect/index.php on line 2

    where line 2 is : include_once “fbmain.php”; what i doing wrong? can you help me please.

    • mahmud ahsan August 19, 2010 at 3:31 am #

      checkout if you place fbmain.php at that directory or not.

      • vadim August 19, 2010 at 6:51 am #

        yes its same directory :
        facebook.php
        fbmain.php
        index.php
        i have this three file in there

  109. SuitUp August 19, 2010 at 8:57 am #

    AWESOME Tutorial!

    But how do you put other data in an array?

    For example if you grant permission to share user_activities. How can you put it in an array like the array $fbme?

  110. Saiful Amri August 25, 2010 at 7:34 pm #

    @Joe says – August 25, 2010 at 12:28 am

    You can find an example of using javascript in this tutorial, please check again…

  111. Christian August 27, 2010 at 11:26 pm #

    Hi! First of all let me tell you that I looked around for lots of tutorials and yours is the only one that helped me!. Now, I’m getting an error when, after been logged using your example in my server and getting an account data, I go back to facebook, log out, go back to the example (which I kept open in another window) and refresh the page…I get an error like this:

    FacebookApiException Object
    (
    [result:protected] => Array
    (
    [error] => Array
    (
    [type] => OAuthException
    [message] => Error processing access token.
    )

    )

    [message:protected] => Error processing access token.
    [string:private] =>
    => 0

    and it goes on. I read that it may be a token expiration problem and they say that I have to get offline_access permissions…so, how do I do that with your code?

    A similar thing happens if instead of logging out from facebook website, I login again with a different account. If I refresh my page I get the same error for 1 sec and then it refreshes with the correct data.

  112. Christian August 27, 2010 at 11:26 pm #

    BTW….thank you so much for the tutorial!

  113. JAH August 30, 2010 at 6:59 am #

    Good, solid example. Very good thanks!

  114. Christian August 30, 2010 at 12:18 pm #

    Hi again, well I found a way around the issue I mentioned before. Since that, in a practical way, this error didn’t interfere with the functionality of the website because the connection with facebook worked it’s just don’t I don’t like an error message printed in half your screen, I removed your Exception routines. Now it doesn’t show the error and it works.

    If anyone has this issue too (read my comment on August 27 11:26pm) and found a way to actually solve the problem and just not hide it please let me know!

  115. Richard September 3, 2010 at 3:48 am #

    Hi Mahmud,

    Thanks for this great tutorial, I have been struggling with this for a while.

    Any idea how to post an event?

  116. John September 4, 2010 at 4:39 am #

    I had this application working on a server through Joynet’s developer program then switched to their paid service and it broke.

    I changed the website config in the Facebook dev app, so its not that. I can change the website back and forth from the old server to the new. The old will always work and the new will not.

    The app running on the new server lets me login into Facebook, accept the extended permissions and then redirects me to the appropriate place but it acts as if I am not logged in.

    Any ideas? I have been going over code and server configs for two days now.

  117. Neetu September 6, 2010 at 12:52 pm #

    Hi,

    Am a beginner and trying a FB application using Graph API. I tried the examples given on this site.

    But always $facebook->api(‘/me’) returns NULL and throws exception. I tried all the suggestions mentioned in the posts but unable to figure out the reason.

    Can anybody please help me.

    Thanks in advance.

    Regards,
    neetu

  118. John September 6, 2010 at 6:34 pm #

    Neetu,

    What is the exception that it throws?

    • Neetu September 6, 2010 at 6:38 pm #

      Hey John,

      Thanks for replying.

      I just solved the issue. It was not resolving the DNS for graph.facebook.com from my server.

      Thanks
      neetu

  119. Martin September 7, 2010 at 12:45 am #

    If someone can help me with this error y dont know what to do…

    i get an FacebookApiException Object

    url http://www.fbatp.webuda.com/index.php

    Please Help

  120. Social Arabia September 10, 2010 at 5:01 am #

    Hi,

    I copied the code as is, but I keep getting the following when I browse the facebook App URL:

    Application Temporarily Unavailable
    The URL http://socialarabia.net/wordpress/fb/phpsdk/src/ returned HTTP code 200 and no data.

    Sorry, the application you were using is experiencing a problem. Please try again later.

  121. Social Arabia September 10, 2010 at 11:07 pm #

    Update:

    i tried debugging the code line by line in the fbmain.php
    I commented all the lines of code and started removing them one by one ( I know.. crazy :))

    it seems I can get away with

    <?php

    $fbconfig['appid' ] = "your application id";

    $fbconfig['api' ] = "your application api key";

    $fbconfig['secret'] = "your application secret key";

    include_once "facebook.php";

    But the minute I add the try statement I get the error code 200 and no data returned!!!

    Any thoughts?

  122. Social Arabia September 11, 2010 at 1:05 am #

    some more Update:

    Ok, the problem is with JSON! i am not an experienced developer but reading carefully through your article and doing some research I implemented this code to see whether I can make JSON calls
    $input = ‘{ “test” : 12121211212121 }';
    $val = json_decode($input, true);
    print $val[“test”];

    and I received an error.. I wonder if I can still make JSON calls on Dotster shared hosting

    Any thoughts anyone?

  123. Dion September 16, 2010 at 5:08 am #

    Superb job of explaining each part. My app was not working before I read this article … now it’s working fine!

    Thanks

  124. Annalivia September 23, 2010 at 10:53 pm #

    Mahmud, your tutorials have been a huge benefit to me! The facebook documentation is rubbish :( If it wasn’t for your excellent tutorials, I still would not even know where to start! Thank you thank you thank you for posting these and explaining everything so well!!

    Something I couldn’t find mentioned in your blog (but maybe its there) is how to post to a Facebook page as the page admin and not as the user. I spend days looking for this, and eventually found some sample code here that works (Thanks to Matt Burton!): http://bugs.developers.facebook.net/show_bug.cgi?id=10005#c139

    Just posting this link here for others, as I have seen many people ask this on the facebook forums, and I can see many people come to your tutorials for help so this might help them too!

  125. Angelnotdie September 24, 2010 at 10:32 am #

    Could you show me how to connect cakephp with facebook?
    I want to use graph api in cakephp, but i don’t understand how to apply sdk-php into cakephp like you have done above…
    Thanks for your help!

  126. SATYA September 27, 2010 at 1:46 am #

    when i am trying to integrate it i am getting this error

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: next is not owned by the application.

    please help me to remove it

    thanks

  127. warshock September 28, 2010 at 10:36 am #

    Hi guys, this is probably a noob question, but im not getting any session or session NULL if i var_dump, can anybody help me?

  128. Jason October 1, 2010 at 12:21 am #

    Hi i was wondering if someone could help me out….. i have read tons of tutorials but none really apply to my situation or i cant get it to work because im not exactly sure on what to do…i know a little about php but im no rocket scientist when it comes to this….. i have tried a bunch of different ways to implement this on my site and im not sure what files i am suppose to edit i am trying to get t he facebook connect on a software called phpbb3…. i have it installed on my server .. most tutorials dont explain or show how to implement this on a forum and since things have changed at facebook in 2010 not many people have updated videos or anything to show how it is donei have been messing with this for about 5 months now with no sucess on getting it to work so if someone could help me out i would be forever greatful you can contact me via email if anyone wants also i already created a developer app … that part was easy all the other stuff is hard and cant figure out..

  129. Henry Tian October 2, 2010 at 3:16 am #

    If anyone hit fatal error complain about:

    Cannot use object of type stdClass as array

    for
    $param = array(
    ‘method’ => ‘users.getinfo’,
    ‘uids’ => $fbme[‘id’],
    ‘fields’ => ‘name,current_location,profile_url’,
    ‘callback’ => ”
    );

    just change ‘uids’ => $fbme[‘id’], to
    ‘uids’ => $fbme->id,

  130. nove October 6, 2010 at 9:17 pm #

    Hello,
    nice tutorial. I wanted to post a message in my Facebook Wall through my site and I used it. It works fine in mozzilla but I can not post anything on IE, safari and Chrome. What could be wrong?
    Thanks

  131. Robbi Bushovisky October 7, 2010 at 6:28 am #

    There is obviously a lot to know about this. I really didnt have a clue. Took me time to read all your posts, at least most of them, but I really enjoyed your blog. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!

  132. Fahim Ahmed October 7, 2010 at 2:32 pm #

    I have written PHP example code for beginner Facebook application developers.
    Easy to use
    Easy to deploy

    Features
    1. Configuration setting config.php
    2. Built-in Admin panel, including following
    Ads Module (Google, Images, SWF, Text etc)
    Users Management, (send message, user listing, delete, etc)
    3. Language Class
    4. Categories management class up to unlimited hierarchy
    5. Other features like ready made rating script built-in .

    For Demo and Download Code
    http://apps.facebook.com/itsiframeapp/

  133. imran October 16, 2010 at 1:29 pm #

    Hey I am trying to get the list of friends of my friends is tehre any way to access them.

    • mahmud ahsan October 16, 2010 at 10:45 pm #

      You’ve to do a trick in this case, when a user logged in, retrieve all his friends and save those ids in your database. So when you need a person’s other friends just retrieve friends ids from your database.

  134. Kartik October 19, 2010 at 3:09 pm #

    How do I request for extended permissions using the Graph API and PHP SDK ?

    • mahmud ahsan October 21, 2010 at 12:45 am #

      Checkout the authentication code where you can easily provide extended permissions.

      • Kartik October 21, 2010 at 1:06 am #

        I checked it but couldn’t find the syntax to ask for extended permission using Graph API and PHP .. Can you point me to it ?

        • doekia October 21, 2010 at 4:04 am #

          May be this can lead you to the proper things:

          public function getMorePermissionUrl($params=array())
          {
          // WARNING: scope here not req_perm – ?!?
          return parent::getUrl(‘graph’,
          ‘oauth/authorize’,
          array_merge(
          array(
          ‘client_id’ => self::getAppId(),
          ‘redirect_uri’ => self::getCanvasUrl(true),
          ),$params));
          }

          That is php_sdk but the same can be achieved thru JS

          Regards,

          • Kartik October 22, 2010 at 12:39 pm #

            So with PHP SDK and Graph API.

            $facebook->api(/oauth/authorize,array(‘read_stream’,’user_birthday’);

            Is this fine ?

      • Kartik October 22, 2010 at 8:52 pm #

        Using Graph API for retreiving user info of a particular user with the UID,

        Can I send multiple UIDs in a single API call ?

  135. jondesantos October 21, 2010 at 6:52 pm #

    Thank you very much! Your posts helped me a lot! :)

  136. Jose October 22, 2010 at 8:23 am #

    yeah, it helped me a lot too, thanks

  137. prasad C G October 22, 2010 at 11:11 am #

    Thank you very much for this tutorial, with this SDK how can we post news and wall with out changing the status

  138. Muhammad R. Babsail October 25, 2010 at 2:59 pm #

    great post, this is what i need.
    anyway, to develop an facebook app i just need PHP-SDK only? i mean, no need to use jscript-sdk ?

    • mahmud ahsan October 25, 2010 at 6:39 pm #

      In step 3, you’ll see javascrip sdk is loaded by the following code.

        (function() {
                      var e = document.createElement('script');
                      e.type = 'text/javascript';
                      e.src = document.location.protocol +
                          '//connect.facebook.net/en_US/all.js';
                      e.async = true;
                      document.getElementById('fb-root').appendChild(e);
                  }());
      
  139. Filip Witkowski October 26, 2010 at 11:24 pm #

    Hello,
    How can I skip login and allow access steps to be automatically. For example if someone is logged in on my website and I have already all information like user credentials and api data?

  140. Kamal October 27, 2010 at 9:43 am #

    Hi, mahmud, Does you tutorial will work on localhost? I’ve tried to copy paste all your code in my localhost, It’s not working at all. But when I try it on my live server, it works very well… Is there any way to make it works on localhost? since it’s not so comfortable to do the stuff on live server. I’d rather test everything from my localhost.

    • Justin Cribb October 27, 2010 at 11:06 am #

      It will not work on localhost unless you setup facebook settings to connect on your project on port 8080. This will work -> localhost:8080. This will not work -> localhost.

  141. imran October 27, 2010 at 7:56 pm #

    Hi
    I am trying to acces the location of my friends and some other information of my friends.I have tried so many ways but i am not being sucessfull to do so. Can any boady help me Plz..

    Imran Athar

  142. Chi-Yao Tseng November 2, 2010 at 1:07 pm #

    Very nice and clear tutorial!
    I can successfully access data with graph api call.
    However, the response time is kind of annoying.
    Each api call costs about 1~2 seconds.
    If a page needs to call api 5 times, user will wait up to 10 seconds.

    Does someone suffer from the same problem and have good workaround?
    Thanks.

    • mahmud ahsan November 2, 2010 at 9:52 pm #

      So better you cache information those are frequently need.

  143. Filip Witkowski November 2, 2010 at 10:02 pm #

    Didn’t anyone changed the api functions to get the user credentials for i.e. xml file (not ask user to type them) ?

  144. Erick November 4, 2010 at 1:05 am #

    So, I managed to put this into a module for Joomla, uhm but Idk why it does not publish. maybe I did something wrong.. o.O I followed ur steps tho..

    Well you can check my website if u want to see it.

    Regards =)
    Erick

    • Erick November 4, 2010 at 1:25 am #

      Nevermind it worked, I guess I had to wait a little while :D.. niice nice :D

  145. lucian November 6, 2010 at 1:32 am #

    hy,
    First of all, thank you for this great tutorial.For two days i’ve tried running this example, but i’m stuck(i’m new with php and facebook apps) ..

    I can’t get the user’s real email address ! I only get facebook proxy email adress… :(
    my application is at: http://www.mty.ro/tombola/index.php

    Thanks!

    • mahmud ahsan November 6, 2010 at 3:44 pm #

      It depends on your user, if user allow his real email address then you’ll get it otherwise you’ll get proxy email. We’ve no control over user’s choice.

      • lucian November 6, 2010 at 11:29 pm #

        well, the thing is that using the same user profile, i’ve installed both my app and the demo here http://thinkdiff.net/demo/newfbconnect1/php/index.php
        and the difference was that for my app, the default option for mail was to permit the use of proxy email, while when installed your demo app, the default option was the real email adress…. I can’t figure out whi this behaviour occurs …

  146. Swift November 8, 2010 at 6:39 pm #

    Hi,
    Its a great tutorial. I could understand the whole FB connect process in 10 min. Thanks for the great work! I appreciate your effort.

  147. Kamal November 8, 2010 at 7:45 pm #

    I’ve successfully implement this code on my localhost, but the results seems very unstable, it often shows SSL connection timeout exception. Althought, not all the time, but almost 70-80% of api calling always resulted with that exception. I’ve add CURLOPT_SSL_VERIFYPEER => false in $CURL_OPTS array, nothing changed. It still showing that annoying exception.

    Is it because I use it on localhost instead of live server?

  148. tessar November 9, 2010 at 10:00 am #

    Thank you! Your posts helped me a lot!

  149. sathish November 9, 2010 at 4:06 pm #

    Mahmud, congratulations for your posts.
    I’m trying to make this thing work in a FB application.
    No problem in chrome and mozzilla, but in Internet explorer 6 when i click login button. Pop up open after logedin with my FB account its shows empty page….

  150. sathish November 9, 2010 at 7:48 pm #

    HI Mahmud i need ur help..Plz guide me.This is my mail id php.sathish@gmail.com

  151. sathish November 9, 2010 at 8:15 pm #

    The same thing occur in Ur Demo URL.In IE 6

    http://thinkdiff.net/demo/newfbconnect1/php/index.php

  152. Justin Cribb November 9, 2010 at 8:30 pm #

    For Sathish

    Facebook does not support IE6.

    • sathish November 10, 2010 at 11:49 am #

      :(

      • Justin Cribb November 10, 2010 at 12:06 pm #

        Move on Sathish…the giants have already moved on, drop IE6.

        If Microsoft is not going to take drastic action, Google will. YouTube, the Google owned video sharing site has long ago announced that it would no longer support IE6. Now Google is taking it one step further by announcing that it will no longer support IE6 on its Google Docs and Google Sites services as of March 1. – http://ow.ly/37hx0

  153. Niks November 13, 2010 at 4:40 pm #

    dear mahmud thanx for the post, it help me to understand a lot
    .

  154. Kim an November 15, 2010 at 12:54 pm #

    Hi mahmud ahsan, can u tell me how to install curl and json extension?

    • mahmud ahsan November 15, 2010 at 11:37 pm #

      It depends on the operating system and server. Please search in google you’ll find the solution.

  155. Cuan November 15, 2010 at 11:18 pm #

    Hi Mahmud

    Thanks for the great tutorial. I have one question, and maybe anyone will be able to help me.I have been using a lot of your code an been looking at a lot of the facebook documentation. My question is, on all the facebook examples, the call contains the access token.

    /me/likes?access_token=…

    I have played around with the code for a couple of weeks, and so far, I have not used the access_token in any of my calls, whether to retrieve info or post.Can anyone tell me why this is, and if its wrong to do so?

    Kind Regards

    • Justin Cribb November 16, 2010 at 7:25 am #

      Hi Cuan! To avoid calling the facebook api to generate oauth token, you save the access token in the database instead. This token may or may not expire depending on the permission you requested from your users. If you include Offline_Access permission, the token will not expire. You can print_r the session and play around with it so you’ll see the difference between having an offline_access permission and not including it in your permission. ^^

      • Cuan November 16, 2010 at 1:27 pm #

        Hi Justin, thank you very much for the reply. My problem is more of understanding when to use access_token in api calls. Like I say, I use a lot of the code on this site, and so far, have not needed to safe the access token at all, or even use it in any of my calls.

        I can send you through some code examples. When you ask for permissions on the login but, does it mean that you can access these things without using access codes.

        Thanks in advance

        • Justin Cribb November 16, 2010 at 1:33 pm #

          You’re welcome. I’d like to explain it further, but I’m currently at the office…sneaking this reply to you haha! You can email me your code samples or inquiries at ian.moone77@ymail.com. I’d be happy to help based on my facebook dev experiences^^

          • Cuan November 16, 2010 at 2:15 pm #

            Thank you very much. Just sent you a message. Thanks

  156. Shishir Mittal November 18, 2010 at 1:24 am #

    Hey,

    Thanks for this lovely tutorial. Well explained!


    Shishir

  157. foil November 20, 2010 at 1:22 pm #

    hello,

    your tutorial is wonderful. could you by chance give a quick example of how to access a friend’s music section of the info page. calling /uid/music returns an array of JSON objects but im not sure how to deal with them in PHP. even a short answer about how to approach this would be very helpful.

    cheers. :)

  158. Nandini Bhaduri November 22, 2010 at 3:09 pm #

    Hi, I created a facebook application called Cellthis. And used the above code. Clicking on the login button gives me the following error –

    An error occurred with Cellthis. Please try again later.

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: next is not owned by the application.

    I think I am doing something wrong while creating the application. Can you please help.

    • Nandini Bhaduri November 22, 2010 at 5:11 pm #

      Fixed it. Thanks for such a great tutorial.

    • Sachin January 8, 2011 at 7:01 pm #

      Hi,
      I am also facing same problem while using php SDK api for facebook connect on my website .

      Error is as follows:

      An error occurred with PHP SDK Unit Tests. Please try again later.

      Please help me

  159. Majid November 24, 2010 at 3:37 am #

    hi,

    I’m try to use facebook to login to my site, which i can but my problem is that i need to get these details.

    Email, first name, last name, location, education, work history, gender, relationship_status.

    Using PHP can this be done as i only can get email, last name, first name.

    Please let me know if i can get all these details .

    Thank you,
    Majid

  160. Jason Peh November 25, 2010 at 11:37 pm #

    Hi,

    I found your tutorial is quite clear but when I try to use your demo codes on my webserver but i got the error below.

    FacebookApiException Object
    (
    [result:protected] => Array
    (
    [error_code] => 77
    [error] => Array
    (
    [message] => error setting certificate verify locations:
    CAfile: /usr/local/share/certs/ca-root-nss.crt
    CApath: none

    [type] => CurlException
    )

    )

    May I know is there any problem is my server configuration? Thanks in advance!

    • ameer December 21, 2010 at 2:56 am #

      Hi, any solutions to this by any chance. I am experiencing the same problem. Thanks.

  161. Rex November 26, 2010 at 10:04 am #

    Woah!… Many thanks! This really helps….

  162. baljeet November 30, 2010 at 6:06 pm #

    Hi, I’m creating a website in php where users can login to their facebook accounts and can post to their fan page wall.

    One of the step in the authentication is to add the facebook app with the fan page. i have the permanent session key, uid, page id etc. Please guide me how to add page with app.

    Thanks in advance.
    Baljeet

  163. baljeet November 30, 2010 at 6:07 pm #

    Hi, I’m creating a website in php where users can login to their facebook accounts and can post to their fan page wall.

    One of the step in the authentication is to add the facebook app with the fan page. i have the permanent session key, uid, page id etc. Please guide me how to add page with app.

    Thanks in advance.
    Baljeet

  164. Brian Ferris December 2, 2010 at 2:04 am #

    YOU MADE MY DAY!!! THANKS A LOT!

  165. Robbye Rob December 2, 2010 at 9:16 pm #

    I am using the $fbme = $facebook->api(‘/me’); code and I never get anything in return.
    What do you think is the root cause for this since everyone uses this for their examples.???

    • Robbye Rob December 3, 2010 at 1:29 am #

      Well looking into this issue, I think it is not allowed by my hosting site…

  166. vinoth December 3, 2010 at 7:49 pm #

    Hi

    i need to get email of the customer ,

    i followed your code , but i can’t get email ,
    kindly help me.

    http://173.203.104.63/football/logins/

    Thanks,
    Vinoth.M

    • mahmud ahsan December 7, 2010 at 4:20 pm #

      Please provide email permission in the authentication process, so that you could retrieve user’s email address using facebook api.

      • Vinoth December 27, 2010 at 3:29 pm #

        Hai Mahmud,

        Thanks for your valuable replies , Now i get user email address and his other basic details.

        Now i need to track his friends list and also track his wall and also i need to invite .

        Kindly help me…

        Thanks & Regards,
        Vinoth.M

  167. wayne December 7, 2010 at 1:43 am #

    I am attempting to create a Fan Page within facebook, is this the tutorial I need to create an application?
    Within the application I simply need to grab a visitor/user of the fan page’s UserId from Facebook. Is this the tutorial for me?

    Please, excuse me being such a newb

  168. Make Pixels December 8, 2010 at 4:59 am #

    You can see the files here http://facebook.makepixels.com/files.txt

    It´s txt file
    If someone has one that will operate normally, please you can send me I really appreciate so much. my email is
    ——
    soporte@makepixels.com

    I can add to your messenger
    Thanks again. :-)

    • mahmud ahsan December 8, 2010 at 2:08 pm #

      Please describe about your problem.

  169. Kunal December 11, 2010 at 12:07 pm #

    Hi
    Looking for a basic Facebook Application Code in PHP.
    Came across you Javascript tutorial and then this PHP one. I haven’t read it yet but it seems it would be easy implementing it.

    I have faced a issue here, I clicked on your demo URL –
    http://thinkdiff.net/demo/newfbconnect1/php/index.php

    but when the page opens, i have given the access permissions and then it loads again and again i.e. refreshing again and again.

    • mahmud ahsan December 11, 2010 at 11:04 pm #

      I’ve just checked and found no problem that you’re saying.

  170. Kunal December 11, 2010 at 12:41 pm #

    Hi tried the code mentioned above and got this error.

    ===========
    Application temporarily unavailable
    Parse errors:

    FBML Error (line 7): illegal tag “body” under “fb:canvas”

    Sorry, the application you were using is experiencing a problem. Please try again later.
    ===========

    Please tell how to proceed for it???

    • mahmud ahsan December 11, 2010 at 11:03 pm #

      The error says don’t use html tag. So avoid it.

  171. Roderick December 12, 2010 at 6:02 pm #

    hi Mahmud,
    thank you a lot for the tutorial ,it is great!
    One question: i included the news feed from facebook (the first page you see when you login ) but that doesn’t show for example that USer B is now friends with User C. do you know how to show that?
    I did this to show the news feed:
    try {
    $newsfeed = $facebook->api(‘/me/home’);
    }
    catch(Exception $o){
    d($o);
    }
    I do get the rest! tHank you very much!

  172. SanTri December 13, 2010 at 4:45 pm #

    Thanks for your nice tutorial. I have created a script which update status of fb-page and is working exactly as per desire. The Only problem is that the content posted via this script is only viewable to admin of that page, for other user cant!!! any solution?

    Access Token Link:

    https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=xxxx&redirect_uri=http%3A%2F%2Fwww.myurl.com/atok.php?return=true&scope=user_photos,email,user_birthday,user_online_presence

    Update status link:

    https://api.facebook.com/method/stream.publish?message=“+opener.document.fstat.status.value+”&target_id=yyyyyy&access_token=returned_accesstoken&format=json

  173. Oscar Gonzalez December 17, 2010 at 1:01 am #

    Just to let you know you saved me lot of time.
    Many thanks!

  174. Adam Thompson December 18, 2010 at 1:00 am #

    I am in the process of programming a custom CMS that will implement connection with various social media platforms. I found this to be a very nice primer to the Facebook graph API. Thanks for the info!

  175. Online TV December 19, 2010 at 1:49 am #

    Thanks for the tutorial!

    I only don’t know and understand how to custom the output content.

    Right now I’m getting all the content into an array as:

    Array
    (
    [location] => Array
    (
    [id] => 115351105145884
    [name] => Cairo, Egypt
    )
    )

    But I don’t want it to be in array …

    how can I custom the output please?

    For example I want something like this:

    $location[‘id’]
    $location[‘name’]

  176. Joe Goble December 19, 2010 at 11:11 am #

    I just wanted to post cause this was so helpful for me. In my PHP file I had some mysql code and for the life of me I couldn’t figure out why I was getting 2 sets of the same data getting inserted into my database each time the file would load. I found out it has to do with this line –
    FB.init({appId: ”, status: true, cookie: true, xfbml: true});

    I added this and it fixed it – session : ,

    I’m assuming it wasn’t finding the session so it would load the the page twice.

  177. Joe Goble December 19, 2010 at 11:14 am #

    My post above got butchered from html. This is what I meant with not safe characters removed.

    FB.init({appId: ‘?=$fbconfig[‘appid’ ]?’, status: true, cookie: true, xfbml: true});

    session : php echo json_encode($session);

  178. Azfar Siddiqui December 19, 2010 at 5:43 pm #

    Great work Mahmud!! .. this really helped me !

  179. Casper December 21, 2010 at 1:28 am #

    Hey Mahmud, thanks! Do you know how put a newline (Enter) in the description (of a post to a users feed)?

    • Kunal December 21, 2010 at 10:49 am #

      I too want to know this.

  180. Gideon December 21, 2010 at 3:51 am #

    Has anyone found a fix for the IE login window bug?
    IE opens the popup, but after you enter username and password the popup just hangs there with a white screen.

  181. saira December 23, 2010 at 9:45 pm #

    Is is possible that i get facebook’s feed through graph APIs, as it is shown when we clicked this link https://graph.facebook.com/me/feed?access_token=

  182. lili edryana December 24, 2010 at 2:22 pm #

    hye.
    i got a problem here. Could you help me?
    This code has been shown when i try to connect through the login button. It’s actually long codes.

    Thank you.

    FacebookApiException Object
    (
    [result:protected] => Array
    (
    [error_code] => 1
    [error] => Array
    (
    [message] => Protocol https not supported or disabled in libcurl
    [type] => CurlException
    )

    )

  183. ammara December 28, 2010 at 2:01 pm #

    Hello,

    i want to change profile picture through my application.as u did update the status through ur application.

    kindllly help me

  184. Imran Athar December 28, 2010 at 7:04 pm #

    Ammara,

    We can not change our Profile Image thorugh Graph or Javascript APi.

  185. Juegos December 29, 2010 at 8:34 am #

    By far the best facebook apps tutorial.

  186. Fernando December 31, 2010 at 2:05 pm #

    There is a way to avoid HTTPS in a free Hosting like 000webhost?…i got “Protocol https not supported or disabled in libcurl” exception…i think is SSL problem.any help? or how i can create and aplication for test purpose,in my own local server (localhost) ???

  187. Aman Durrani December 31, 2010 at 7:30 pm #

    Great work Done Sir
    i was looking for this thing nd finally i got it

    thanku So much for posting such a great post

  188. Imran Athar January 3, 2011 at 2:51 pm #

    @Ammara.
    Upload a Picture on Profile or in an Album.
    ————————————————-
    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’,
    array(
    ‘source’ => ‘@FILENAME’,
    ‘message’ => ‘Messsage’
    )
    );
    } catch (FacebookApiException $e) {
    print_r($o);
    }

  189. Shah Alom January 3, 2011 at 4:24 pm #

    ohh Great !!! This is better than facebook’s own documentation. I like it Boss. Thanks.

  190. clark davvid January 4, 2011 at 2:06 pm #

    Nice post, great detail. I would have liked to see the costs that are associated to it so I could add to my business case justifi cations to use the technology. Keep up the good work! Great Job!!! Informative and attention keeping!
    facebook connect applications

  191. Dries January 4, 2011 at 11:42 pm #

    Hi, I’m redesigning my site and i will include facebook comments on my wordpress instead of the normal comments.
    I am looking for a way to get the postcount from my facebook comments on my index page but can’t find how.

    I’ve looked everywhere and stumbled on this site. By the looks of it, you guys know a lot more from programming than I do :)

    Can someone help me? or lead me in the right direction?

  192. uut3 January 5, 2011 at 8:42 am #

    thanks for sharing dude,
    i like this so much,
    great tutorial,
    :D

  193. Noha January 5, 2011 at 5:26 pm #

    Thanks for your demo, I’m a new bee to PHP and facebook development so i find a very hard time to get started ..
    Your code is simple and understandable BUT
    For unknown reason to me any graph api call doesnt return anything
    meaning i included facebook.php ( the latest PHP sdk ), checked that JSON and cURL are enabled on my server and yet its functions dont return anything at all !!!!
    Just a facebook canvas blank page !!! any idea why is that may be i miss something

  194. sashi January 6, 2011 at 12:07 am #

    Hi, iam getting the following error when i click on the facebook login icon:

    API Error code: 191
    The specified url is not owned by the application
    redirect_uri is not owned by the application

    What could be the problem…. ?

    • Noha January 6, 2011 at 3:30 pm #

      Well Iyar this msg error when I didn’t assign the correct callback URL
      You should be careful when putting ur callback URL that points to the application on yr server
      http://www.domain name.com/folder name/
      I hope that works with u :)

    • mahmud ahsan January 6, 2011 at 9:05 pm #

      May be facebook’s recent change. I will check it later.

  195. Facebook Lead Generation Script January 10, 2011 at 6:15 pm #

    Great work, I’m very excited about the future of Facebook Open Graph and the web!

  196. kamran January 12, 2011 at 7:04 pm #

    would you help me how do I invite friends using FB Connect??????? I worked but its not properly functional..

  197. Eugenio January 15, 2011 at 3:03 am #

    I tried to use the php sdk example as is, and it works.
    I tried to just change this line in example.php

    $loginUrl = $facebook->getLoginUrl();

    to

    $loginUrl = $facebook->getLoginUrl(array(‘req_perms’ => ‘email,read_stream’));

    but it seems that nothing changes, facebook doesn’t ask me additional permissions for email and read_stream, and

    print out just the public info.

    Did I make a mistake?

    Thanks for the post!

  198. Friedrich Zohmann January 17, 2011 at 1:41 pm #

    Hi,
    Does anyon know if there is a replacement in the new Graph API for these calls from the old REST API:
    $facebook->api_client->users_isAppUser($user_id);
    $facebook->api_client->users_hasAppPermission(‘publish_stream’, $user_id);
    The 1st one checks if a user has authorized the APP and the 2nd one checks if the user already has authorized the “posting on wall” permission for the APP.
    I dont know how I can check that with the new PHP SDK.
    thanks, Friedrich