Published on Oct 15, 2010

People Search using Facebook Graph API – Find Users through Name or Email

People Search using Facebook Graph API

People Search using Facebook Graph API

If you wanna develop a website where your users will search for a person with name or email address to find out more information about the person, then you might want to search through different social network API’s with your user’s query and get the results back to your user. In this post I will show you how to fetch a list of users from facebook through name or email address using the Facebook Graph API. I’m going to use PHP in the back-end with the CURL library extension for the API calls.

In this process your users don’t need to login to facebook or even don’t need to have any facebook account. The process goes as follows:

Create the Facebook Application
Create a Facebook Application using the Facebook Developer Tool. After creating the app go to the application settings and get the values of the parameters saying “Application ID” and “Application Secret”, we will have to use them later.

Authenticate Your Application
As Facebook Graph API uses OAuth 2.0 for authorization, so we need to authenticate the application for the permissions of some Graph API calls we gonna use. To do this, lets jump to a new tab in your browser and copy and paste the following url into the address bar.

https://graph.facebook.com/oauth/authorize?client_id=...&redirect_uri=...&scope=offline_access,read_stream

Replace the … part after client_id with the value of “Application ID” you got in step 1 and replace the … part after redirect_uri with the url of your php page. Remember you also need to set this redirect_uri as your facebook application setting “Site URL” to make it work properly. An example url might look like this:

https://graph.facebook.com/oauth/authorize?client_id=1234567&redirect_uri=http://www.example.com/mytest.php&scope=offline_access,read_stream

after you hit enter in your browser to goto the url you’ve just specified, this will ask you to login to facebook (if needed) and after you login, a box will appear something like below for you to grant access rights permission you specified in the scope parameter of the url. The details of scope parameters that you can use is available here.

A Sample Facebook Authentication Dialog

A Sample Facebook Authentication Dialog

Click on the Allow button to allow your application to be able to use the Graph API search functionality. After this you will be redirected to the redirect_uri you specified before, with a code sent to that page in get parameter. This url will look something like the one below:

http://www.example.com/mytest.php?code=e3b7fb0d311786a055a51618-10……..

We will need this code to request an access_token, which will be used each time we gonna query the Graph API.

Getting the access_token
Now you have the authentication code to query the Graph API. This will return you an access_token which we will need to provide with each API call. The following code segment gets the access_tokenfrom the Graph API:

function callFb($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
));

$result = curl_exec($ch);
curl_close($ch);
return $result;
}

$url = "https://graph.facebook.com/oauth/access_token?client_id=...&redirect_uri=...&client_secret=...&code=...";
$access_token = callFb($url);
$access_token = substr($access_token, strpos($access_token, "=")+1, strlen($access_token));

Here we’re querying the API url https://graph.facebook.com/oauth/access_token with the client_id (the Application ID of step 1), redirect_uri (the url of your current PHP page), client_secret (the Application Secret of step 1) and code (the code value returned in step 2). This request will return the access_token in the following format:

access_token=ACCESS_TOKEN_VALUE

So to get the access_token value we take the sub-string after the equal (=) sign.

Get the search results
Now we have the access_token, we can request the search API. The following code segment will show you how to do that (assuming your form’s textfield name is ‘search’ and using the post method):

$url = "https://graph.facebook.com/search?access_token=$access_token&q=".urlencode($_POST['search'])."&type=user";
$ret_json = callFb($url);
$users = json_decode($ret_json, true);

Here we are querying the API url https://graph.facebook.com/search with the access_token we got from step 3, our query string q which is the name or email address our user wants to search and the search type=user which is for people search. This call will return a json formatted output which can then be decoded into a php array for further processing.

For example you can access the name of the first user by accessing $users[data][0][name], or the user’s facebook id through $users['data']['0']['id']. You may also show the user’s profile picture like the following:

<img src="https://graph.facebook.com/<? echo $users['data']['0']['id'];?>/picture?type=small" alt="" />;

Here the type parameter can have values “square”, “small” or “large”. Now you may also want to get more details about the user. As you’ve got the user id so you can query the graph API in similar way with the user id to get more information about the user. The next article will let you know, how to get more information about the user, his/her shares and status on facebook.

Update for Localhost XAMPP Development

For testing this in your local server,  add 2 extra lines into the callFb function right after “$ch=curl_init();”

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

Thanks to Honza Hudec for the suggestion :)

Update, Facebook API Change

Facebook recently has deprecated offline_access and the access_token will no longer be permanent, but will rather be long lived (2 months). If you are using an old app that was not created recently, then you also need to migrate to oAuth 2.0 in your application advanced settings. So for now the code you get from facebook is not gonna work for more than 2 months. So you need to update your code and access_token using the above procedure every 2 months. You can automate this process using your facebook account to make sure your app gets the updated access_token when the previous access_token is expired.

Author: Masum
Tags: , , , ,

50 Comments + Add Comment

  • Jorge Luis Sala

    November 4, 2010 at 8:34 am

    Hi Mahfuzur!

    This tutorial is excelent ! I took days to find there. Thank you for posting.

    I like to ask you a question about this. I do every step like you indicate, but when “curl_setopt_array” function executes the script hung up, and minutes later throw error.

    Do you know what can it be?

    I really thanks for your time man. Sorry for my poor english.

    • Masum

      November 5, 2010 at 6:39 am

      Hi,
      Can you please tell me exactly what error message you are getting? What I can guess is the $url you are sending to the callFb() function is not in correct format. Did you replace the “…” parts in the url with the correct values of your client_id, redirect_uri, client_secret and code?

  • Tom Somerville

    November 4, 2010 at 9:26 am

    Hi,

    Nice article works nicelely, Just one question why didnt u use the PHP SDK facebook offers?

    Tom Somerville

    • Masum

      November 5, 2010 at 6:16 am

      Hi,
      The php sdk will need each user to login to facebook and authenticate the application to get the access token for the search queries to work. In this implementation it’s not required for the user to have even a facebook account to do the search.

      Of course you can use the sdk after you get the access token from the steps described here, but I didn’t want to use the sdk where there are simpler alternatives for this particular implementation. Using the sdk sounds logical to me when you need to implement something that has to deal with the graph API for much more data and social interactions.

  • Paul

    December 25, 2010 at 1:57 pm

    Hi,
    Great code!

    But… sometime we get an authentication error and sometimes we do not:
    Access Code: “error”: { “type”: “OAuthException”, “message”: “Code was invalid or expired.” } }

    Any suggestions?

    • Masum

      December 27, 2010 at 2:38 pm

      Hi,
      Did you get the code using scope “offline_access” and accepted the permissions properly just as described here?

  • 333Giberno

    January 7, 2011 at 8:51 pm

    hi, Mahfuzur Rahman, nice script. But I am failed to get the `$access_token`, where is the problem? thanks.
    ` $url,
    CURLOPT_RETURNTRANSFER => true
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $url = “https://graph.facebook.com/oauth/authorize? client_id= {Application ID} &client_secret= {Application Secret} &redirect_uri= http://www.mysite.com/mypage.php &scope=user_photos,user_videos,publish_stream”;// I have put my Application ID and Application Secret in it.
    $access_token = callFb($url);
    $access_token = substr($access_token, strpos($access_token, “=”)+1, strlen($access_token));
    echo $access_token;// echo is empty
    }`

    • Masum

      January 8, 2011 at 4:43 am

      Hi,
      well the url you are using is not for getting the access token, but for getting the code and then you need to get the access token using the code you get from this url. please follow the instructions described here properly and i see you also forgot to mention the “offline_access” property in the scope parameter.

      • 333Giberno

        January 8, 2011 at 2:18 pm

        Thanks, Masum, now I can return back my $access_token;
        but the image resault is empty. this is the whole code: http://pastie.org/1440090

        • Masum

          January 10, 2011 at 7:12 am

          Well, the way you are trying to get the access token will make the users of your service to login to facebook and authenticate! You are certainly not gonna do that right?

          As I’ve mentioned in this article, you need to get something called the “code” to get the access token from the graph api for backend use and not bother your users to login to facebook to use your service.

          You need to get the “code” yourself using your own fb account. Follow instructions 1 & 2 described here properly to get the “code” (a long string something like e3b7fb0d311786a055a51618-10……..) from the graph api. then use that code to request the access token each time using the callFb function. Wish this helps you to understand what I’m saying, Thanks :)

          • 333Giberno

            January 10, 2011 at 10:57 am

            Hi Masum, this time, there is no error alart, but the search result is still empty. where is the problem for I am not a smart man, the code in http://pastie.org/1444880 .
            And, do you have any idea, how to get the “code” automatic(use php code)? thanks many.

          • Masum

            January 10, 2011 at 12:05 pm

            from your posted code, what i could see is you didn’t mention any “redirect_uri” in the url for getting your access token. one thing i should mention is you might get an access token which is limited to certain graph api calls. so to get an access token that will work properly with people search, you need to get the code using “read_stream” and “offline_access” permissions with a correct “redirect_uri”. and also use the same “redirect_uri” when you call for the access token. can you echo your $access_token and $ret_json so that i can see whats happening with your code?

            And ofcourse you can get the code using php. As the graph api calls the “redirect_uri” with the “code” in get parameter, so you can also get the “code” with php. But I don’t see any need to do that for this implementation as you are using “offline_access”, this “code” will never gonna expire in your lifetime :)

          • 333Giberno

            January 10, 2011 at 2:00 pm

            Thanks a lot, now I have got the picture from the user. that is a great script, cheers. : – }

  • Honza Hudec

    January 20, 2011 at 9:47 pm

    thanks, thanks, thanks :o) after several hours of digging in the internet resources, this is the most comprehensive source

    btw I had to add 2 extra lines into callFb function right after “$ch=curl_init();”:
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

    as it didn’t work on my XAMPP Apache+mySQL bundle which I run on my localhost for development.
    Hope this will help to anyone :)

    • Masum

      January 21, 2011 at 5:17 am

      Thanks a lot for your suggestion :) But I think something is wrong with your PHP installation. Most likely, you don’t have the ENTRUST intermediate cert needed to validate SSL certificate. Setting CURLOPT_SSL_VERIFYPEER to false simply disables certificate check. You shouldn’t do that in production. You may use this in your local development server, but I think you shouldn’t disable it where you deploy your codes.

    • Honza Hudec

      February 1, 2011 at 11:29 pm

      hello, I have another question:

      I am trying to perform search via oauth on linkedin.com but it still redirects me to do allow_connection_page, and after that I can perform desired search query by linkedin API call.

      Can you advise me how to do it without logging in?
      My idea is to enter some name “John Walker” and see results from facebook, linkedin, … with names, photos, …

      Any help is very appreciated. Thank you.

      I already posted my question to linkedin developer site here: http://developer.linkedin.com/thread/1439?start=30&tstart=0

      • Masum

        February 3, 2011 at 12:25 pm

        As far i know, linkedin API do not provide offline_access facility. But i think there is a workaround. You may follow this tutorial here to know how to get an access token: http://www.formatix.eu/en/php-linkedin-api-zend-oauth.html

        and then store the serialized version of $token variable from Step4 of this tutorial. For later usage, un-serialize it and get http client from it.

        • Guest

          May 21, 2011 at 6:35 pm

          yes, it does.  the linkedin access token is permanent by default. 

  • Péter Nagy

    May 5, 2011 at 8:27 pm

    Hi,

    I’ve been trying your solution but instead of the access token I always get the following error:

    {“error”:{“type”:”OAuthException”,”message”:”Error validating verification code.”}}

    Maybe the API doesn’t work anymore that way?
    I have a hard time trying to make the scipt work offline (no user auth) since the type=client_cred method does not allow me to search for user emails.

    • Masum

      May 6, 2011 at 8:14 am

      Hi,

      This solution still works for applications developed by me. I think you are missing some part of the instructions provided here. My method is not like client_cred type. It is using scope offline_access and read_stream. Please check the procedure described here properly to get the correct “verification code”.

      Thanks

    • Ricardo Mayerhofer

      December 7, 2011 at 9:57 pm

      Most likely the redirect_uri is wrong. It must be the same used to generate the code, and check tha back-slash at the end.

  • Anonymous

    June 15, 2011 at 10:26 am

    Thanks ! This is the best articles I’ve found for facebook authentication ! Thanks a lot!

  • Anonymous

    August 12, 2011 at 6:07 am

    The code is very good that I can get first 20 search result. I would like to know how to get the next 20 result, and so on?

    • Masum

      August 12, 2011 at 9:00 am

      Hi,
      If there are more results, then in the returned json, you’ll get a key named “paging”
      where you’ll get the next and previous paging urls. If you look at those urls then you’ll find an additional “since” and “until” parameter for previous and next pages in the query.

      You can also control the number of results per page by using an additional
      “limit” parameter with the query to graph API. Thanks

  • thger

    September 21, 2011 at 5:44 pm

    Hi, 
    Thanks for the article. 
    I’ve been trying your solution but i keep getting the following error:
    {
    “error”: {
    “message”: “Invalid redirect_uri: Given URL is not allowed by the Application configuration.”,
    “type”: “OAuthException”
    }
    }May i know how to solve this error. Thanks

    • Masum

      September 22, 2011 at 2:16 am

      Hi
      You need to set your Site Url in the facebook application to use the same address as your redirect_uri.
      Thanks

      • thger

        September 25, 2011 at 4:43 pm

        Thanks. I managed to solve that. But there is another error coming up now.
        “error”:{“message”:”Error validating verification code.”,”type”:”OAuthException”}}I had followed your instructions but there is still this error. And does this “code” expire? Because everytime i get the code, it will regenerate a new one for me. Any idea how to solve this error. 
        Thanks alot.

        • Masum

          September 26, 2011 at 7:16 am

          The verification code should be taken using the offline_access scope as described here. So this code will not expire until you are generating a new code using this method again.

          Please generate this code only once and then use this code every time you request an access_token from the facebook API. And for any other request to the graph API, just use the access_token for the period the access token is valid. Normally the access token will be valid for one hour. When it expires, then send an http request to get a new access_token using the code you’ve generated before.

          Don’t request the code every time, request the access_token using the code you’ve generated once and then use that access_token for the period it is valid.

  • Randy

    December 6, 2011 at 5:36 pm

    Thank you so much for this article. I have been banging my head for days.
    My question is i can only get this to work and find results if i put my last name.
    if i put firstname lastname or email it always finds 0.
    i really need to get this working searching by email. has anyone been successful at that?

    • Masum

      December 7, 2011 at 7:22 am

      Hi, searching by email won’t work if the user is unsubscribed from public search in the privacy settings.

Leave a comment

Sponsored