Fetch Online Friends List With Facebook Graph Api

🦖 This post was published in 2011 and is most likely outdated.

This article is a step-by-step PHP tutorial explaining how to use the Facebook PHP SDK to get the list of the online friends of the current user.

To get the list of online friends in PHP, first you need to authenticate users with their Facebook account asking for the permission friends_online_presence. This is done using the Facebook PHP SDK (see on github) adding friends_online_presence to the scope while generating the login link:

require "facebook.php";
$facebook = new Facebook(array(
    'appId'  => YOUR_APP_ID,
    'secret' => YOUR_APP_SECRET,
));

$user = $facebook->getUser();
if ($user) {
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

if (!$user) {
    $args['scope'] = 'friends_online_presence';
    $loginUrl = $facebook->getLoginUrl($args);
    
    // display login link
}

Then, if the user is logged in, you can make the request:

if ($user) {
    $fql = "SELECT uid, name, pic_square, online_presence
            FROM user
            WHERE online_presence IN ('active', 'idle')
            AND uid IN (
                SELECT uid2 FROM friend WHERE uid1 = $user
            )";

    $result = $facebook->api(array(
        'method' => 'fql.query',
        'query' => $fql,
    ));
    
    // read results
}

The results will be like:

Array(
    [0] => Array(
        [uid] => 1536397056
        [name] => Quentin Pleplé
        [pic_square] => http://...jpg
        [online_presence] => active
    )
    [1] => ...
    [2] => ...
    ...
)

The online_presence property can take 4 values: active, idle, offline, or error.

Comments