Sunday, 7 July 2013

PHP code for facebook Login on your website

Follow these steps

Step 1
Include the attached file (facebook.php) in your PHP page

Step 2
In your PHP page create a session with facebook


// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => 'your app id',
  'secret' => 'your secret key',
  'cookie' => true,
));
$session = $facebook->getSession();

$me = null;
//var_dump($session);
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

Step 3
Now $me will have a full array in case you are already logged in on fb or it would be null. So, just check $me and accordingly display the login / logout link
 

// login or logout url will be needed depending on current user state.
if ($me) {
  print_r($me); //print the user info 
  echo $logoutUrl = $facebook->getLogoutUrl();
} else {
  echo $loginUrl = $facebook->getLoginUrl();
}

No comments:

Post a Comment