Brent Deneau
Brent Deneau

Reputation: 31

Determine if a user has liked my page using Facebook PHP SDK?

My search has come up empty because when you search for "Facebook" and "like" I get all kinds of other results.

I have an app that is only on my company's Facebook page. In that app I need to find out if the user has liked the company's page. I'll show one thing if not and another thing if so. How can I do this using the Facebook PHP SDK v.3.1.1?

Upvotes: 3

Views: 13074

Answers (5)

Nadeem Khan
Nadeem Khan

Reputation: 3434

It can be done this way:

<?php
    require('facebook.php');
    $config = array(
         'appId' => 'your facebook app id',
         'secret' => 'your facebook app secret code',

        'allowSignedRequest' => false
    );
    $facebook = new Facebook($config);
    $user_id = $facebook->getUser();
    if (isset($user_id)) {
        try {           
            $likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');             

            if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
            {
                echo 'Thank you for liking our fan page!';                   

            }             
            else {                                       
                 //show something else                   
            }
        } catch (FacebookApiException $e) {
            $login_url = $facebook->getLoginUrl();
            echo '<a href="' . $login_url . '">Please click here to login into your Facebook account.</a>';
            error_log($e->getType());
            error_log($e->getMessage());
        }
    } else {
        $login_url = $facebook->getLoginUrl();
        echo '<a href="' . $login_url . '">Please lick here to login into your Facebook account</a>';
    }
    ?>

The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display what ever you want if user hasn't liked your fan page.

Upvotes: 4

Jon Gallup
Jon Gallup

Reputation: 317

Old topic, but wanted to weigh in as I have recently learned a lot about how to do this and have had to put it into practice.

Have a look at this link: http://nickring.com/blog/2012/11/facebook-fan-gate-using-php/. It uses the signed_request variable as some of the other responses show, but it shows how it does not require requesting the signed_request variable via $_REQUEST.

The one main thing to remember is that signed_request is only available when the PHP script accessing signed_request is run within Facebook. If you run this script outside of Facebook in a script attempting to use the Facebook API, it will return an empty array.

Here's an example - the following script will run when you go to this address: https://www.facebook.com/yourFacebookPage/app_xxxxxxxxxxxxxxx with 'xxxxxxxxxxxxxxx' being the app ID.

// Check if the user has liked us on Facebook, require the Facebook SDK
require_once('linked/facebook/facebook.php');

// Setup the Config
$config = array(
    'appId' => 'xxxxxxxxxxxxxxxxx',
    'secret' => 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
    'cookie' => true
);

// Create a Facebook SDK instance
$facebook = new Facebook($config);

// Get the signed_request variable that we so desparately need
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];

// Make sure that it worked
if (!empty($signed_request))
{
    // Get the signed_request information
    if ($like_status == 1)
    {
        // Wo0t! Show the FB fan only page stuff here
        
    }
    else
    {
        // Show the 'Please like us page'
        $page = file_get_contents('pages/facebookLikeUs.html');
        
        // Finish the page
        echo $page;
        exit();
        
    } // End if ($like_status == 1) ELSE Clause and IF
    
} // End if (!empty($signed_request)) IF Clause
else
{
    // Damn, it didn't work. Show an error
}

The above script is the script that is called from the URL set in the Canvas URL in the "App on Facebook" section of the App's settings. The facebookLikeUs.html page is simply a page asking them to click "Like" to continue. If I'm in a situation that I want them to be redirected back into a website that requires the Facebook like I simply replace the // Wo0t! section with something like this:

    // Wo0t! They're all set, establish some cookies, get a cookie, and redirect back to the PHD program site
    setcookie('fbls', $signed_request['page']['id'] . '-' . $signed_request['user_id'], time() + 300);
    $redirectURL = "http://www.myurl.com/theScriptIWantToReceiveTheUserFromFB.php";
    
    // Since Facebook really wants to keep us in the page, we need to create a page that will automatically break out of FB
    $page = file_get_contents('pages/facebookRedirectBack.html');
    
    // Replace some stuff
    $page = str_replace('$redirectURL', $redirectURL, $page);
    
    // Output the page
    echo $page;
    exit();

With the facebookRedirectBack.html page being this:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
window.top.location.href = '$redirectURL';
</script>
</body>
</html>

If you're looking to have a bit more security on this, you can have the redirecting PHP script write some cookies and attach them to the URL such that the receiving script must compare the cookies and the URL params then delete the cookies after they've been read.

Hope this helps as I personally haven't found any consistent information on this subject.

Upvotes: 0

Karun
Karun

Reputation: 66

$signed_request = $_REQUEST['signed_request'];

    function parsePageSignedRequest() {
            if (isset($_REQUEST['signed_request'])) {
                    $encoded_sig = null;
                    $payload = null;
                    list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
                    $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
                    $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
                    return $data;
                }
            return false;
            }
        if($signed_request = parsePageSignedRequest()) {
            if($signed_request->page->liked) {

            $this->assign('verify', $signed_request->page->liked);
            } 
            else {
                echo "Please click on the Like button to view our Coupons!";
                jexit();
            }
    } 

I hope this will help you :)

Upvotes: 1

Drew Dahlman
Drew Dahlman

Reputation: 4972

This should work for you! I had to do a lot of these types of pages so I created a really simple way of creating like gated pages. https://github.com/DrewDahlman/FBVersion

Enjoy!

Upvotes: 2

Jeff Wooden
Jeff Wooden

Reputation: 5489

You can do this using FQL. You'll also need to make sure that you have the user_likes permission set.

I pulled this example from an older app that is now offline, it may need to be changed depending on what Facebook has changed in their last round of updates. Lately I've been using javascript and I subscribe to the edge.create event.... just replace the page_id with your page's id and give it a try

$checkIfUserLikePage =  $facebook->api(array(
    "method"    => "fql.query",
    "query"     => "select uid from page_fan where uid=me() and page_id=1234567"
));
$checkIfUserLikePage = sizeof($checkIfUserLikePage) == 1 ? true : false;

Upvotes: 3

Related Questions