Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?
EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first
Is it possible to check if a user already likes my facebook fanpage from my website with Javascript or PHP?
EDIT: I need a solution, so the user doesn't need to authenticate / allow some persmissions first
The simplest way would be to call the Graph API to get the /me/likes
connections (note you have to require the user_likes
permission). Then go through each and compare id
with the ID of your page.
Assuming you're using the official Facebook PHP SDK, and have an instance of the Facebook
object set up (see Usage section in the aforementioned page), the following code can be used to find out if the user is fan of Daft Punk:
$our_page_id = '22476490672'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
if( $page['id'] === $our_page_id ) {
$user_is_fan = true;
break;
}
}
Now, you can further work with the $user_is_fan
variable.
In JavaScript, the code would be very similar. Using the official JavaScript SDK's method FB.api
(again, assuming you have taken of the authentication):
FB.api('/me/likes?fields=id', function(response) {
var our_page_id = '22476490672';
var user_is_fan = false;
var likes_count = response.data.length;
for(i = 0; i < likes_count; i++) {
if(response.data[i].id === our_page_id) {
user_is_fan = true;
break;
}
}
});
Note that here we're using an asynchronous request and callback, so the code using the user_is_fan
variable must be inside the function.