How to import Facebook friends to website

I've got a website that has users and users can add each other as friends. Lately, I've been seeing a lot of web apps that have a function where you can import your friends from Facebook directly into their web app. How is this type of import of the Facebook friend list implemented?

I looked in the Facebook API docs, and can't really find anything directly on point to this.

Presumably I would use the Facebook API to pull a list of the user's friends. From there, how would I then find users on my site that are members of that list? Does this type of scheme only work with other users that have already used the Facebook friend search themselves, so that you can tie a Facebook account to them?

There really doesn't seem to be much out there on this topic, even though I've seen a lot of sites doing it, so any help, no matter how basic, would be much appreciated.


The basics of what you'll need for this center around registering your site as "a Facebook application" and making use of the Graph API.

Take a look at the "Login with Facebook" section of this page. Basically, when you register your "application" you will have an application ID and an "application secret" (which is just a string of characters, and must never be made public or anybody with it could spoof as your application). The example on the page shows a small amount of JavaScript to initialize the application from your website, at which point you're good to go for Facebook integration.

Just below that is an example of the "Login with Facebook" button, which is what your users would use to indicate that they wish to allow your site to access some of their Facebook data (the Friends list, for example). You can highly customize the specific permissions your site requests from the user within that login tag, and your users would be presented with a prompt like this one specifically asking for permission to allow your site to access their Facebook data.

Looking back at this page again (though it may be on other pages as well, the Facebook documentation changes a lot), scrolling down a little further you find a simple example (in PHP) for very basic Facebook integration. The example page presents the user with a "Login with Facebook" button and reloads itself after the button is clicked (by subscribing to the correct Facebook API event in JavaScript). Upon reload, the user now has an encrypted cookie (assuming the user agreed to the permissions request) which the example page can read.

The "application secret" is used to decrypt the cookie, which contains the user's Facebook ID and the access token which authorizes your site to make requests for that user's Facebook information. Using the access token in Graph API requests will grant you permission to receive the data from those requests.

Graph API requests are just GET requests which return JSON data, so once you have the access token (and the user ID as a starting point) you can make such requests anywhere you want. They can be made client-side in JavaScript (along with using Social Plugins and other Facebook widgets) to "Facebookify" your users' experience on your site without exposing much, if any, data or responsibility to your site. Or the requests can be made from your server-side code on the back end for the purpose of storing requested data and using it as your site sees fit (such as the Friends list).

An API request to get a list of Friends would be something like this:

(However, you'd replace the me in the path with the Facebook ID of the user whose Friends you wish to retrieve, and replace your_access_token with the actual access token. Example links for your own account, assuming you're signed in to Facebook, can be found on this page.)

The Graph API (as the name suggests) extends outward across the social graph of Facebook data. Any JSON object which comes back with an id can be requested in its own API request to see more of its information. Any piece of information you want, such as the email addresses of the user's Friends, will be available if and (hopefully) only if the permissions of both the user and the user's Friend in question allows this. (Sorry, but if the user's Friends have specifically said that their Friends can't grant access to this information, then it's not available.)

So, once your users grant your site the requested permissions to view their Facebook data, you can harvest whatever data you want (and are allowed to access) that's available in the Graph API. (I hate using the word "harvest" there, but you get the idea. Act responsibly, of course.) So your process, from the perspective of the user in any given instance, would be:

  1. Ask the user to Login with Facebook, requesting specific permissions.
  2. Receive those permissions from the user (otherwise the process ends here).
  3. Make back-end Graph API requests from your server code to get the relevant information from the user's Facebook social graph.
  4. Present the user with options that you could make sense of (such as matching email addresses or even names with users you already have), be it users you already have (hey, this Friend of yours is on our site, would you like to say hello?) or invites to your site (we don't have a record of your Friend visiting our site, click here to invite them!), etc.
  5. The user then continues to interact with whatever functionality your site is presenting in this matter.

Make sense? As I mentioned, the documentation for all of this on Facebook changes a lot (I found several dead links within their own site while writing this). Their programmatic interfaces change fairly often as well. They may develop easier ways to do this, but once you get set up and going and abstract out the Graph API calls and all that, it becomes pretty straightforward to integrate your site(s) with Facebook.

You are able to get the friend's list of members who login into your website using Facebook Login. HOWEVER, only friends who are also registered on your website will be shown. (In Facebook term, only friends who are also using the same app)

From facebooks developer's page you are able to get the following codes.


$fb = new Facebook\Facebook([
  'app_id' => '{app-id}', // Replace {app-id} with your app id
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email','user_friends']; // Optional permissions (THIS IS WHERE YOU GET THE PERMISSION FOR FRIEND'S LIST)
$loginUrl = $helper->getLoginUrl('', $permissions);

echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';


$fb = new Facebook\Facebook([
  'app_id' => '{app-id}', // Replace {app-id} with your app id
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.2',

$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';

// Logged in
echo '<h3>Access Token</h3>';

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';

// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId({app-id}); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here

if (! $accessToken->isLongLived()) {
  // Exchanges a short-lived access token for a long-lived one
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";

  echo '<h3>Long-lived</h3>';

$_SESSION['fb_access_token'] = (string) $accessToken;

// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.

At login.php you can see the following line

$permissions = ['email','user_friends']; 

This will prompt user for permission to access the friends who are also using the app.

This code will get the friend list from graph

 try {
            // Returns a `Facebook\FacebookResponse` object
            $response = $this->fb->get('/me?fields=id,name,email,gender,user_friends,', $this->token);
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();

The codes are all sample and are for reference only so you get the idea of what's happening in the backend. I highly recommend you take a look at

Should you have further questions with regards to the flow you can then create new question to get your answers.

Update: Handling user_friends <- this is what you are looking for

Upon login using Facebook on to your website, the logged-in member will be given a permanent unique id to your website.

When you request for the user_friends graph of that member, Facebook Graph will return a list of user objects for friends who are using this app as well. And those objects includes the user id (which is unique to each app), from the ID you will be able to link up friends who know each other within your app.

Example User A (ID: 1234) and User B(ID: 5678)

1) User A login to your website using Facebook.

2) You try to request user_friends from Facebook of User A but it returns nothing.

3) User B register and login to your website using Facebook.

4) You try to request user_friends of User B and Facebook graphs returns user A's ID 1234.

From there you are able to understand 5679 and 1234 are friends and you are able to design your database around that to associate your members as friends.

Need Your Help

Google maps removing controls

javascript html css google-maps

I am attempting to create a Google map of my company location. I used the link button on the Google maps page. Everything's fine, but when I shrink the map to 200 x 200 all the maps controls take o...

Adding arrows to scrollbar

html css scrollbar arrows

I'm trying to add arrows to the x and y axes of the scrollbar, here's my scrollbar: