2

Hello super awesome people from stackoverflow!

I need help with this php script.. I want to get facebook id from user when it enters his facebook profile link in the input box. example of the profile link: https://www.facebook.com/profilename. I have a script that collect the "profilename"from the url and save it to the $username but now i need the script to convert that profilename to the facebook ID of that profile and save it to the $username. Now i know you can get facebook id manually easy when you right click on the user Profile Picture than click on Copy link adress and the last number after .(dot) is user profile ID..Or another method is to scan the page for <meta property="al:ios:url" or <meta property="al:android:url" That will also get user ID. And this is the site that has that working script. http://findmyfbid.com/

This is my code now: As you can see it only takes last part of the url.. Please help to make it right to convert that profilename to ID and save it to $username .Thank you.

 /* CHECKING */
        if (isset($_POST["urlCheck"])) {
            $url = $_POST["urlCheck"];
            $urlParts = explode("facebook.com/", $url);
            $username = GetOnlyUsername($urlParts[1]);

            if (filter_var($url, FILTER_VALIDATE_URL) !== false) 
                exit("success");
            else 
                exit("error");              
        }

        /* TAKING INFO */
        if (isset($_POST["urlGetData"])) {
            $url = $_POST["urlGetData"];
            $urlParts = explode("facebook.com/", $url);
            $username = GetOnlyUsername($urlParts[1]);

            $name= GetData($username);


    function GetOnlyUsername($username) {
        if ((strpos($username, 'profile.php?id=')) !== false) {
            $username = str_replace("profile.php?id=", "", $username);  
            if ((strpos($username, '&fref=ts')) !== false) {
                $username = str_replace("&fref=ts", "", $username); 
            }
        } else if ((strpos($username, '?')) !== false) {
            $test = explode("?", $username);
            $username = $test[0];   
        }
        return $username;
    }
Couch_Ech
  • 41
  • 1
  • 1
  • 4
  • So given an input of `https://www.facebook.com/profilename`, do you want to 1) Extract the `profilename` from the URL or 2) Extract the `profilename` and convert it to numeric Facebook ID? – jehna1 Mar 12 '16 at 10:53
  • Correct! When user input the https://www.facebook.com/profilename i want only that "profilename" to be converted to Facebook ID and saved to that function GetOnlyUsername($username),because the rest of the script works fine when the input is https://www.facebook.com/ID. So the answer is 1) Extract the profilename from the URL and convert it to numeric Facebook ID. – Couch_Ech Mar 12 '16 at 11:28
  • For better code readability you could use different naming for user id and username. I'd suggest you'd use the variable names `$userid` and `$username` respectively. Also you'd want to name your function from `GetOnlyUsername($username)` to e.g. `GetUsernameFromFacebookURL($url)`. I'd also advice to use comment-first approach to coding, because now it's pretty hard to figure out the logic you're trying to accomplish with that code. – jehna1 Mar 12 '16 at 11:33
  • The code as you see now only extracts "profilename" form the url. Lets say the input of url is looking like this _italic_https://www.facebook.com/profilename?fref=ts the function GetOnlyUsername($username) extracts only that profilename and removes the rest trom the url... Now i need when that function is finished to only continue converting that "profilename" to ID. I hope that make sense now. – Couch_Ech Mar 12 '16 at 11:45

1 Answers1

9

Now your function GetOnlyUsername has some odd results when provided with an URL:

echo GetOnlyUsername('https://www.facebook.com/profilename'); // outputs https://www.facebook.com/profilename

To make the function more clear, I'd suggest to rename the function so it is more easily understandable and have a clear set of validations. Here's how I would do it:

function GetUsernameFromFacebookURL($url) {
    /**
     * Taken from http://findmyfbid.com/, the valid formats are:
     * https://www.facebook.com/JohnDoe
     * https://m.facebook.com/sally.struthers
     * https://www.facebook.com/profile.php?id=24353623
     */
    $correctURLPattern = '/^https?:\/\/(?:www|m)\.facebook.com\/(?:profile\.php\?id=)?([a-zA-Z0-9\.]+)$/';
    if (!preg_match($correctURLPattern, $url, $matches)) {
        throw new Exception('Not a valid URL');
    }

    return $matches[1];
}

Now, converting the Facebook username to Facebook ID is more tricky. Now, there are many duplicates of this question without a resolved answer, which gives us a hint that it cannot be done via the official API.

I'm guessing findmyfbid.com and alternatives are using some non-official API to fetch the data (like scraping facebook.com site directly). I must say I discourage you for doing this, since the non-official APIs tend to break without notice and scraping the site might be forbidden by the Facebook's terms of service.

HOWEVER if this is just for your hobby project and you don't care if it breaks within a week, I found the following code to fetch the user's ID from the website:

function GetUserIDFromUsername($username) {
    // For some reason, changing the user agent does expose the user's UID
    $options  = array('http' => array('user_agent' => 'some_obscure_browser'));
    $context  = stream_context_create($options);
    $fbsite = file_get_contents('https://www.facebook.com/' . $username, false, $context);

    // ID is exposed in some piece of JS code, so we'll just extract it
    $fbIDPattern = '/\"entity_id\":\"(\d+)\"/';
    if (!preg_match($fbIDPattern, $fbsite, $matches)) {
        throw new Exception('Unofficial API is broken or user not found');
    }
    return $matches[1];
}

So this piece of code changes the user agent to some obscure string, which, for some reason unknown, triggers a positive reaction when fetching facebook.com/username, exposing the user id in a piece of JS code.

Please note that using this script is most likely against Facebook's terms of service, it is not an official api but just a hack, and it may stop working in any given moment without any notice. Facebook might also randomly throw you a CAPTCHA page, which also breaks the code execution.

But for now it seems to work just fine.

Community
  • 1
  • 1
jehna1
  • 3,110
  • 1
  • 19
  • 29
  • This script not work anymore, facebook api does not support getting id from username and the findmyfbid.com can not find id of users who disable search engine in setting. However, http://fbid.co can find the numeric id of users whose search engine setting disabled. Does anyone know how to do it? – Truong Hua Sep 04 '17 at 08:57
  • @TruongHua just tested it myself and it seems to work just fine. How did you test the script? – jehna1 Sep 05 '17 at 09:47