How to Determine if Facebook User 'Likes' a Certain Page

bimbom22 picture bimbom22 · Jan 16, 2011 · Viewed 17.4k times · Source

Is there any way to determine if a Facebook user 'likes' a certain page with the API Facebook offers currently?

UPDATE

I have been trying to get this to work via the PHP graph API for a while now with this code.

$fbconfig['appid'] = '***';
$fbconfig['api'] = '***';
$fbconfig['secret'] = '***';

try {
    include_once "facebook.php";
} catch(Exception $o) {
    echo '<pre>';
    print_r($o);
    echo '</pre>';
}

$facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret'],
  'cookie' => true,
));

$session = $facebook->getSession();
$me = null;

if ($session) {
    try {
        $uid = $facebook->getUser();
        $me = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        d($e);
    }
}

if($me) {
    try {
        $likes = $facebook->api('/me/likes');
    } catch(Exception $o) {
        d($o);
    }
}

However, the session is always null, even though I am logged in.

Apparently, the above code is only good for Facebook Connect "Canvas" applications, I am calling this code from an FBML tab on a Facebook "Page" through an AJAX call to my server.

I'm not very familiar with all of the Facebook development terminology.

How can I get the current user's 'likes' in my situation?

Answer

Racoonsteak picture Racoonsteak · Feb 23, 2011

There's a way to do that without requesting permission and without using any kind of API.

If you have PHP:

<?php
$signed_request = $_REQUEST["signed_request"];

list($encoded_sig, $payload) = explode('.', $signed_request, 2);

$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

$app_data = isset($data["app_data"]) ? $data["app_data"] : '';
$_REQUEST["fb_page_id"] = $data["page"]["id"];
$access_admin = $data["page"]["admin"] == 1;
$has_liked = $data["page"]["liked"] == 1;
?>

You can use $has_liked to wrap your fan-specific content

<?php if($has_liked) : ?>
fan-specifc
<?php else : ?>
for non-fans only
<?php endif; ?>

replaces

<fb:visible-to-connection>
fan-specific content
<fb:else>
for non-fans only
</fb:else>
</fb:visible-to-connection>

It's very useful and convenient, since asking for permission is a turn-off.