Facebook API – Get friends list

Facebook API – Get friends list

70 339565
Facebook API – Get friends list
Facebook API - Get friends list

Facebook API – Get friends list

In our recent tutorials I told you how to import your contacts from google. Today I decided to make similar tutorial, but for facebook. I think that it can be very interesting for you to get a list of your friends. We are going to use Facebook’s API (javascript api) to build today’s example.

Firstly, we should create our own new application at Facebook. Please follow this link and click ‘Create New App’ button at the left top:

Faceboog Friends API - step 1

We should select our App Name and click ‘Continue’ button. We’ve just got our own api key:

Faceboog Friends API - step 2

Now, please pay your attention to Basic Info block, we should type our App Domains and Site URL params:

Faceboog Friends API - step 3

That’s all, click ‘Save Changes’ button, and lets start coding !


Live Demo

[sociallocker]

download in package

[/sociallocker]


Step 1. PHP

Now, please create an empty index.php file and put next code:

index.php

<?php
$sApplicationId = 'YOUR_APPLICATION_ID';
$sApplicationSecret = 'YOUR_APPLICATION_SECRET';
$iLimit = 99;
?>
<!DOCTYPE html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
    <head>
        <meta charset="utf-8" />
        <title>Facebook API - Get friends list | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <header>
            <h2>Facebook API - Get friends list</h2>
            <a href="https://www.script-tutorials.com/facebook-api-get-friends-list/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </header>
        <img src="facebook.png" class="facebook" alt="facebook" />
        <center>
            <h1>Authorization step:</h1>
            <div id="user-info"></div>
            <button id="fb-auth">Please login here</button>
        </center>
        <div id="result_friends"></div>
        <div id="fb-root"></div>
        <script>
        function sortMethod(a, b) {
            var x = a.name.toLowerCase();
            var y = b.name.toLowerCase();
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        }
        window.fbAsyncInit = function() {
            FB.init({ appId: '<?= $sApplicationId ?>',
                status: true,
                cookie: true,
                xfbml: true,
                oauth: true
            });
            function updateButton(response) {
                var button = document.getElementById('fb-auth');
                if (response.authResponse) { // in case if we are logged in
                    var userInfo = document.getElementById('user-info');
                    FB.api('/me', function(response) {
                        userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
                        button.innerHTML = 'Logout';
                    });
                    // get friends
                    FB.api('/me/friends?limit=<?= $iLimit ?>', function(response) {
                        var result_holder = document.getElementById('result_friends');
                        var friend_data = response.data.sort(sortMethod);
                        var results = '';
                        for (var i = 0; i < friend_data.length; i++) {
                            results += '<div><img src="https://graph.facebook.com/' + friend_data[i].id + '/picture">' + friend_data[i].name + '</div>';
                        }
                        // and display them at our holder element
                        result_holder.innerHTML = '<h2>Result list of your friends:</h2>' + results;
                    });
                    button.onclick = function() {
                        FB.logout(function(response) {
                            window.location.reload();
                        });
                    };
                } else { // otherwise - dispay login button
                    button.onclick = function() {
                        FB.login(function(response) {
                            if (response.authResponse) {
                                window.location.reload();
                            }
                        }, {scope:'email'});
                    }
                }
            }
            // run once with current status and whenever the status changes
            FB.getLoginStatus(updateButton);
            FB.Event.subscribe('auth.statusChange', updateButton);
        };
        (function() {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            document.getElementById('fb-root').appendChild(e);
        }());
        </script>
</body>
</html>

Now, please pur your application id (and secret) in the beginning of our code, and only after lets review our rest code. In the beginning I prepared a small html code:

<center>
    <h1>Authorization step:</h1>
    <div id="user-info"></div>
    <button id="fb-auth">Please login here</button>
</center>
<div id="result_friends"></div>
<div id="fb-root"></div>

We will display short info about logged in member in ‘user-info’ element. The button (id=fb-auth) will be used as Login/Logout button. And finally, we will display our facebook’s friends in the last one div (id=result_friends).

Now please review our JavaScript code. In the beginning we perform initialization of FB object with our application id. After, we add event handler to our Login/Logout button. We we are not logged in – the script will ask you to login (with your account credentials). If we are logged in, the script will evoke API method /me/friends in order to get a list of our friends. As you can see – we use limits (99 by default) to avoid very long listings. Once we get it (our friends) we display them on the screen.

Step 2. CSS

In order to stylize our output I used next styles:

#result_friends {
    margin: 0 auto;
    overflow: hidden;
    width: 900px;
}
#result_friends h2 {
    text-align: center;
}
#result_friends div {
    border: 1px solid #888;
    box-shadow: 3px 3px 0 #000;
    float: left;
    margin-bottom: 10px;
    margin-right: 10px;
    padding: 5px;
    width: 275px;
}
#result_friends img {
    float: left;
    margin-right: 10px;
}

Live Demo

Conclusion

I hope that everything is clean in today’s code. If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!

SIMILAR ARTICLES


70 COMMENTS

  1. Hi There,

    Thakyou for the great tutorial! I am nearly there but am having some issues.

    I am hosting the site on wamp server (127.0.0.1)

    When I press the authorise button, nothing occurs?

    On facebook, I have assigned the site url as “http://127.0.0.1/” and have left the domain blank.

    Where have I gone wrong?

    Thankyou in advance!

    • Hello Jay,
      I think that it would be better to test it with remote host, just because of API keys (they should be registered with remote website)

  2. Hi Andrew,

    Tried it again with localhost before preparing to remote host it, worked perfectly! Technology is funny.

    Cheers for the great tutorial! Helped me and many others heaps!

    Cheers,
    Jay

  3. hello sir how are u
    I want to redirect friends onclick to another page. Means when we get the friends link after that when i click on particular friend it go on the another page on which i want to redirect it. For all the friends the page is same. For every friend i want to redirect it on same page.

    • Hi Gaurav,
      If you want to add custom links to your friends, you can easily modify code in line 63, where the script composes the value of ‘results’. Just add your link here.

  4. Hi there,
    i have a problem with this js, how can i get list of random friends and limit example to 5 ?
    Thanks in advance.

    Best Regards

  5. hi.. i implemented the above.. but its not getting login window on click of Please Login Here button.. may i know how long will it take to propagate the changes on the server…

    thanks,,

    • Hello saanvi,
      It can be in case if something wrong is in cookies, try to logout in facebook first, and then – try again our demonstration

    • Hi chandra,
      I can recommend that you try it at any remote host (rather then localhost). Just because you have to get your api keys (but before – you should point url of your website)

    • Hello,
      By default it returns only ID and Name of a member (look: http://developers.facebook.com/docs/reference/api/FriendList/).
      If you need to extract addition information about members, you will need to enhance this script. You will need to obtain information about every member in enumeration.

  6. I am run your code in localhost. but after i run it show a errors in console in firebug “Invalid Application ID: The provided Application ID is invalid.” . Any problem with me ? please help me to fix it. Thanks

    • Hello Raj, please make sure that you use correct API keys for your own domain (by the way, your own demo which you pointed in your comment – works well)

  7. Hey,

    I would like to set so I send each picture links to the person’s facebook link. How would you set that up?

    If you know how please let me know.

    • Hi Daniel,
      response.link is a link to your profile page (on facebook), this is for code that is below:
      FB.api(‘/me’
      But if you are looking how to add a profile link for your friends, you can make an extra call (in the place where you list your friends) to facebook:
      FB.api(‘/__profile_id__’
      to obtain his public info (with a profile link).

  8. Hi, it’s really useful, just what i was looking for!

    I’m a little noob about web development….That’s the matter i have:

    I have an html table, in that i do sql connections, inserts, updates, when users clicks on friends photos, etc.
    the problem is that, i have implemented your code, and its really cool for me, but i can’t merge my old php code, with the javascript you do!

    At first, Thank u very much!
    max

  9. I done it this is nice code wow i like it dude………………………………………………

  10. Hi,
    Its working fine , i want to get their emails also please provide code for this……

    thanks in advance………….

    • Hi Srinivas,
      Unfortunately, facebook doesn’t return emails. When we send the ‘/me/friends’ request, it returns only two params: id (Facebook ID of the friend) and name (Name of friend of current user)

    • Hello Chetan,
      Unfortunately Facebook doesn’t provide this information about your friends. But, you can get your own email using the ‘/me’ request.

  11. Hi,
    I want to display my friends list from facebook account in a separate website. Is it possible to do it? If yes, can you please tell me which sdk/API should be used.

    Thank You

  12. HI, admin.

    At first time, It’s SUCCESS!!!!!!!!!!!!!

    and next time(after 15 minutes) It’s NOT WORKING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    WHAT SHOULD I DO????

  13. This is great peace of code you have for beginners for getting started. I was trying it on localhost, first it didn’t worked for me, as clicking the signin button did noting, but when I updated the facebook app and added the site as http://localhost , then it worked like charm.

    Sharing my experience, so it could be helpful for anyone else here.

  14. i hv downloaded your archives…
    bt i don’t get anythng on click of the button….
    i m a fresher to PHP

  15. while creating i am getting one error ..pls help me..

    error is;

    app domain should not contain protocol information..

    tia……….

    • Hello Murugan,
      Please double-check that you did everything correctly in your first steps when you created your FB application.

  16. I hosted the css file, index.php and html page at:
    http://www.virtualbeach.com/facebook/picture.htm
    and nothing is happening. It asks me to login in, but nothing is happening.

    • I also tried just the index.php code:
      http://www.virtualbeach.com/facebook/index.php
      and still nothing happened

      A bit frustrated here.

  17. Hi Mitch,
    Your demo contains two PHP variables (it seems that you didn’t replace them to actual values)

  18. Hii….

    Sir , how can i get my friends photos,tagged photos into my code?

    if you have some code please let me know.
    thank you

  19. Hi there,

    your code is working nice for importing the contacts of app owner but when i try to use it for fetching other Facebook user contacts, it does not work.

    am i missing something??

  20. Hi,

    Thanks for the script.
    How can i get the user latitude and longitude?
    Ex. if a user is logged in into my site and have acknowledge my app, to ask it to share location and as result to get latitude and longitude.

    How can this be done?

    Thanks again,
    Teem

    • I suppose that your script is already contains the table of your members in database? You also need to store latitude and longitude of your members. In this case you will be able to display it.

      • hello,

        I am using “var todays_date = Date();” for fetching Today’s date and time. but how would i implement this in sort function which is made by you. I had modify your sort fuction for fetching birthdays from Today but it won’t show mi any result.

        Please Help and give me solution.

        waiting for your reply

        Thank You
        :)

        Regards,
        Mayur Vartak
        Mumbai(India)

  21. Hi Mayur,
    You might have an error in your modified sorting function. What is your code for the ‘sortMethod’ function?

  22. hi,

    Really excellent concept for hardworker, its working nice.

    I have to retrive Birthdays of all friends.

    ‘/me/friends?fields=id,name,birthday’ using this i have retrive all my friends birthdays because i am the admin of my app, but if some other user want to access my page then he gets only friend list not a birthdates. So how to show birthdays when some another user wants to get that using login. what kind of permission has to set for other user so they can access friends birthday. please reply.

    Thank You

    Regards,
    Mayur Vartak
    Mumbai(India)

    • Hello Mayur,
      You are on the right way, however, I recommend that you refer to the ‘Extended Profile’ permissions at https://developers.facebook.com/docs/reference/login

      • Hello,

        Thank You. I have got the result, i have set the scope which required for obtaining a birthdays.

        My another query is,
        How to Fetch the friends birthday using FQL?
        I am Using this FQL statement “SELECT name, birthday FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())” for obtaining a result. It gives proper output in Graph API Explorer but in my page it gives output in “Array ( [0] => Array ( [name] => Mayur [birthday] => January 1, 1990 ) [1] => Array ( [name] => Andrey [birthday] => January 1 ) [2] => Array ( [name] => Andrew [birthday] => January 1, 1995 )”
        such way. and so on.
        Tell me how would i shows this in well manner.
        Reply.

        Thank You

        Regards,
        Mayur Vartak
        Mumbai(India)

  23. Hi Mayur,
    I think that you may display the ‘birthday’ value somewhere near the members.

Leave a Reply to Amit Dhorajiya Cancel reply