What are the best practices for structuring PHP code to ensure proper functionality when checking if a user has liked a Facebook page?
To check if a user has liked a Facebook page, you can use the Facebook Graph API to retrieve the user's likes and then check if the desired page is in the list of likes. It's important to structure your PHP code in a way that handles errors gracefully and securely, such as using try-catch blocks for error handling and validating user input.
<?php
// Your Facebook app credentials
$app_id = 'YOUR_APP_ID';
$app_secret = 'YOUR_APP_SECRET';
$access_token = 'USER_ACCESS_TOKEN';
// Get user's likes
try {
$response = file_get_contents("https://graph.facebook.com/v12.0/me/likes?access_token=$access_token");
$likes = json_decode($response, true);
// Check if user has liked the desired page
$page_id = 'PAGE_ID';
$liked_pages = array_column($likes['data'], 'id');
if (in_array($page_id, $liked_pages)) {
echo 'User has liked the page.';
} else {
echo 'User has not liked the page.';
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>