Created
May 5, 2011 20:46
-
-
Save ANorwell/957889 to your computer and use it in GitHub Desktop.
Server-side FB login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'facebook-php-sdk/src/facebook.php'; | |
// Create our Application instance (replace this with your appId and secret). | |
$facebook = new Facebook(array( | |
'appId' => '', | |
'secret' => '', | |
'cookie' => true, | |
)); | |
// We may or may not have this data based on a $_GET or $_COOKIE based session. | |
// | |
// If we get a session here, it means we found a correctly signed session using | |
// the Application Secret only Facebook and the Application know. We dont know | |
// if it is still valid until we make an API call using the session. A session | |
// can become invalid if it has already expired (should not be getting the | |
// session back in this case) or if the user logged out of Facebook. | |
$session = $facebook->getSession(); | |
$me = null; | |
// Session based API call. | |
if ($session) { | |
try { | |
$uid = $facebook->getUser(); | |
$me = $facebook->api('/me'); | |
} catch (FacebookApiException $e) { | |
error_log($e); | |
} | |
} | |
// login or logout url will be needed depending on current user state. | |
if ($me) { | |
$logoutUrl = $facebook->getLogoutUrl(); | |
} else { | |
$loginUrl = $facebook->getLoginUrl(); | |
} | |
?> | |
<!DOCTYPE html> | |
<html xmlns="http://www.w3.org/1999/xhtml" | |
xmlns:fb="http://www.facebook.com/2008/fbml"> | |
<head> | |
<!-- the facebook login button --> | |
<?php if ($me): ?> | |
<a href="<?php echo $logoutUrl; ?>"> | |
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif"> | |
</a> | |
<?php else: ?> | |
<div id="fb-root"></div> | |
<script src="http://connect.facebook.net/en_US/all.js#appId=208341082530964&xfbml=1"></script> | |
<fb:login-button width="200" max-rows="1"></fb:login-button> | |
<script type="text/javascript"> | |
window.fbAsyncInit = function() { | |
FB.init({ | |
appId : APP_ID, | |
session : SESSION_JSON, // don't refetch the session when PHP already has it | |
status : true, // check login status | |
cookie : true, // enable cookies to allow the server to access the session | |
xfbml : true // parse XFBML | |
}); | |
// whenever the user logs in, we refresh the page | |
FB.Event.subscribe('auth.login', function() { | |
window.location.reload(); | |
}); | |
}; | |
</script> | |
<?php endif ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment