我需要在我的网站上持久登录,我使用FB连接通过FB登录。我使用PHP SDK 3。有任何方法如何使持久登录?我认为,我将不得不结合PHP SDK和JS SDK,但我不知道如何做到这一点。
PHP-SDK示例文件with_js_sdk.php
为您提供了一个良好的开端:
<?php
require '../src/facebook.php';
$facebook = new Facebook(array(
'appId' => '191149314281714',
'secret' => '73b67bf1c825fa47efae70a46c18906b',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
现在,根据您的应用程序,您可能希望使用订阅auth.authResponseChange
事件来始终确保您"知道"当前用户的最新状态(仍在登录…等):
FB.Event.subscribe('auth.authResponseChange', function(response) {
window.location.reload();
});
或者您可以选择在需要用户操作时检查,在这种情况下,您将使用FB.getLoginStatus()
方法:
function call_to_action() {
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
// proceed with your flow
} else {
// no user session available, someone you dont know
// trigger FB.login() ...etc
}
});
}
现在您总是将成员相关的内容放在if($user)
语句中:
<?php if($user) { ?>
<p>s3cr3t data</p>
<?php } else { ?>
<p>Please login!</p>
<?php } ?>