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:

  1. 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.
  2. 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.

  3. 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_token from 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.

  4. 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">

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.

If you have time, then have a look at my implementation of this people search in StatusBin People Search. Just type in any name or email address in the search bar and click the people link in the results page to see the results :)

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.

Related Posts

About the Author: Mahfuzur Rahman

Masum is currently the Director of Application Development at Mukto Software Ltd. Involved in the development of Social Web Applications and iOS/Facebook Games. Likes to deal with new technologies, web server platforms and doing interesting stuffs at IdolBin Labs. You might also like to read more here about masum

50 Responses + Add Comment

  • Hi,

    Search people via email was working for me, but today it is not working, curl request return empty array, I checked you demo(http://status.idolbin.com/people.php), and it seems to be also not working by email, but working by name, Can you please tell me why this happens

    • Looks like it’s a bug recently introduced by Facebook. Following is the filed bug:

      https://developers.facebook.com/bugs/292220680814266

      Though they have said they fixed it, you can see the comments section, there are people like you and me having the same problem recently. Let’s report this issue to let them consider it to reopen.

      Thanks

      • Thanks Masum,

        its working good now. looks like they fixed the bug. :)

  • Guys,

    Its not working for me again. Any ideas?

    • What’s not working please? Can you be a bit more specific? Did you follow the procedure described here properly?

  • is it possible to get user info without accesstoken, i am having email address of user. basically i want to create validation for user exist in facebook

    • Nop, access_token is mandatory to query the user info from email address. You can have a long lived access_token using the offline_access permission for your developer account and then use that access_token for queries to the API. Long lived access_token normally lasts for approximately 2 months. You can get the access_token using the procedure described here. 

  • HI guys,

    This is not working anymore. Any new ideas on this?

  • Hi thank for your helpful article, it looks like those codes don’t work any more… Am I correct? because my script used to work and now it doesn’t work any more…

    • Yes it still works. If your code do not work anymore, then I think you need to update the facebook token “code” once again. To do so, follow the procedure in step-2 above and use the updated token “code” to query the graph api.

      • I updated the facebook token “code” again and the search returns 0 results

  • 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?

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

  • 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

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

      • 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.

        • 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.

  • 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?

    • 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

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

  • 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.

    • 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

    • 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.

  • [...] Facebook Status Search using idolbin.com [...]

  • [...] People Search using Facebook idolbin.com [...]

  • [...] People Search using Facebook idolbin.com [...]

  • 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 :)

    • 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.

    • 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

      • 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.

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

  • 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
    }`

    • 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.

      • 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

        • 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 :)

          • 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.

          • 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 :)

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

  • 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?

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

  • Hi,

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

    Tom Somerville

    • 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.

  • 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.

    • 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?

  • [...] Read more: People Search using Facebook Graph API – Find Users through Name … [...]

  • [...] Read the rest of this news story here [...]

  • [...] need an access_token. I’ve already discussed on how to get an access_token in my post titled People Search using Facebook Graph API – Find Users through Name or Email. So now we can use the following code segment for searching through the status updates and user [...]

  • [...] already seen in my previous post how to Find Users through Name or Email using Facebook Graph API. The steps 1-3 of that post has shown how we can get the access_token for the API requests to work [...]

Leave a comment

 

The only paradox of this world is, you know the world with your 5 basic sense organs, and also you know those organs through themselves!!
IdolBin Thoughts