简体   繁体   中英

Facebook logout with PHP SDK?

This example is actually copied from Facebook.

When I access the page the behavior is strange: The "login" first seems to work fine. Then it displays the 'Logout' link. But when I click it I get the exact same screen again, with the 'Logout' link again. Refresh also gets to the same screen.

Checking with Facebook, however, it DOES logs me out.

If I shut the browser and reopen it, the 'Login' is now correctly displayed.

<?php

require 'facebook.php';

$facebook = new Facebook(array(
  'appId' => 'xxxxxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));

$user = $facebook->getUser();

if ($user) {
  try {
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

if ($user) {
  $params = array( 'next' => 'http://xxxxxxxxxx' );
  $logoutUrl = $facebook->getLogoutUrl($params);
} else {
  $params = array( 'redirect_uri' => 'http://xxxxxxxxxx' );
  $loginUrl = $facebook->getLoginUrl($params);
}

?>

<!doctype html>
<html>
  <head></head>
  <body>

    <?php if ($user): ?>
      <a href="<?php echo $logoutUrl; ?>">Logout</a>
    <?php else: ?>
      <a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
    <?php endif ?>

    <?php if ($user): ?>
      Picture = <img src="https://graph.facebook.com/<?php echo $user; ?>/picture">
      User Object = <?php print_r($user_profile); ?>
    <?php else: ?>
      User is not Connected.
    <?php endif ?>

  </body>
</html>
$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
    setcookie( $key, $value, $past, '/' );
}

you can try this code. It will just destroy all cookies saved from your site. Its working for me..!

Create a file logout.php

<?php 
session_start();            //start session
$_SESSION = array();    //clear session array
 session_destroy();      //destroy session
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Log Out</title>
</head>

<body>
<p>You have successfully logged out!</p>
<p>Return to the <a href="....index.php">Home</a> page</p>

</body>
</html>

And change your code where you check user status

if ($user) { 
    $params = array( 'next' => 'http://....../logout.php' );
    $logoutUrl = $facebook->getLogoutUrl($params);
} else {
  $loginUrl = $facebook->getLoginUrl();
}

Use $logoutUrl for logout the user.

<?php if ($user): ?>
<?php echo "Welcome, ".$me['first_name']. " " .$me['last_name']   ." <br />";
      echo "Id: " . $me['id'] ." <br />";  ?>

<a href="<?php echo $logoutUrl; ?>">  Logout </a> <br />

<?php else: ?>
  <a href="<?php echo $loginUrl; ?>"> 

   <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif"> </a>  
 <?php endif ?>

Hope it will work fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM