Get your own Facebook status

in Programming

Facebook seems to have changed things again and to access your status information it's not enough to parse your RSS feed any more. Because there seems to be no RSS feed... It makes perfect sense from the privacy point of view but makes our lives a bit more complicated.

With the new API to access any of your or other user's data you have to create a Facebook application and authorise that application to use your data. As my goal is to make my status publicly available I also have to grant my application an offline access.

To get that authorisation key we create a very basic page that requests user permissions and prints out the authorisation key once permission is granted.

Modified example from Facebook:

// your app id from app settings page
$app_id = "11111111";

// your app secret
$app_secret = "sdfsdfdsfdsfdsfdf";

// url facebook will post data to 
$my_url = "http://dashasalo.com/fbauth.php";
   
session_start();
$code = $_REQUEST["code"];

if (empty($code)) {
    $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
    $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
    . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
    . $_SESSION['state'].'&scope=user_status,offline_access';

    echo("<script>top.location.href='" . $dialog_url . "'</script>");
}

if ($_REQUEST['state'] == $_SESSION['state']) {
    $token_url = "https://graph.facebook.com/oauth/access_token?"
        . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
        . "&client_secret=" . $app_secret . "&code=" . $code;

    $response = file_get_contents($token_url);
    $params = null;
    parse_str($response, $params);

    echo("Auth tocken =  " . $params['access_token']);
} else {
    echo("The state does not match. You may be a victim of CSRF.");
}

If everything goes ok you will get your authentication token printed out. Copy it and past into the following code:

$appId = "11111111";
$appSecret = "sdfsdfdsfdsfdsfdf";

// auth tocken we have just printed out
$authToken = 'AAAAAABBBBBBBCCCCCCDDDDDDD';

// your facebook user id
$userId = '568864222';
        
$graphUrl = "https://graph.facebook.com/".$userId."/statuses?limit=1&access_token=" . $authToken;

$statusMessage = json_decode(file_get_contents($graphUrl), true); 
echo ($statusMessage['data'][0]['message']);

The code above will print out your latest status update. If you want to get the list of all your statuses just remove limit from the url.

$graphUrl = "https://graph.facebook.com/".$userId."/statuses?access_token=" . $authToken;