How to Check if a User is Following Your Facebook Page in PHP
Social media optimization is really essential these days and awarding your site users some points or badges for liking your Facebook fan page is a nice trick to swiftly increase your Facebook fan base. In order to award a user some social bonus, we first need to check whether that user has actually liked the Facebook fan page or not. In order to check this we need the user to login into its Facebook account and allocate all the necessary permissions that our Facebook app will ask (OAuth 2.0).
In case you are NOT OK with user giving the permissions you can skip this tutorial as this tutorial specifically requires OAuth permissions from the users. And, if you are OK with OAuth permissions and your site happens to be a PHP based website, follow this step by step tutorial to easily detect whether a user has liked your fan page or not:
Create a new Facebook app here. Enter the URL of your site in Settings->Platform->Website->Site URL and note down the ‘App ID’ and ‘App Secret’ as we will be using these in step 5!
Download Facebook PHP SDK from here. Extract the files and place it in the same folder with the file in which you will paste the code given in the step 5 below!
Get your Facebook Fan Page ID using this tool.
Step: 4 (Optional)
Generate Facebook like box code for your page from here. You can display this like box if a user hasn’t already liked the page.
After 1, 2, 3 and 4 steps are complete, you can check if user has liked a page or not with the following code:
The user will click on the “Please click here to login into your Facebook account.” text which will redirect it to our Facebook app’s (created in step 1) permissions page, once the user grants the permissions to the app, the code will fetch user’s data and will display the likebox if user hasn’t liked the fan page.
If the user has already liked the page then it will display the thank you message (and will run some custom code included in this section to award some points/badge to the user).
In order to award points only once (so that users cant get points again and again by liking and unliking the page), you can attach a Boolean field (with a default value of 0) with all user accounts which you can turn to 1 once the bonus points have been awarded. An additional conditional check at line 14 in the code given above like “if (!empty($likes[‘data’] && $userfield != 1 ))” will do the trick.
You can also print a message like “You already got the bonus for liking the page!” for users that have already got the bonus points by adding another if statement like this “if (!empty($likes[‘data’] && $custom_user_field == 1 ))”.
Feel free to discuss any issues that you may face in the comments section below!