If you want to get the current logged in user on the server side, the best way I've found to do this is to try to make an API call:
try {
$response = $facebook->api('/me');
}
catch (FacebookApiException $e) {
//User not logged in
}
If the call is successful you now have access to the logged in user id, access token, name, and some other basic stuff (ex. $facebook->getUser() or $facebook->getSession()). Otherwise if you catch a FacebookApiException, you know the user is not logged in and will need to redirect the user to get an access token. The simplest way is just redirect to the url returned by $facebook->getLoginUrl() (http://github.com/facebook/php-sdk/blob/master/src/facebook.php line 322) which you can pass in required permissions:
$facebook->getLoginUrl(
array('req_params' => 'email,publish_stream',
'next' => 'http://www.redirct-upon-login.com',
'cancel' => 'http://www.redirect-if-user-clicks-cancel'));
You can basically do the same thing in Javascript (which I prefer since there's a popup dialog/window instead of a redirect):
FB.login(function(response) {
if (response.session) {
if (response.perms.indexOf('publish_stream') != -1) {
//User has logged in and given us publish_stream permissions
);
else {
//User has logged in but not given us publish_stream
}
}
else {
//User is not logged in
}, {perms:'offline_access,publish_stream'});
To answer your other question on the example.php, it looks like the login button should only be shown if no user is logged in. Otherwise, it shows a logout button.
With regards to redirects, that's basically how OAuth need to work if it is to serve the purpose of securely allowing a third party to take actions on a user's behalf (your app posting on the user's wall for example). Facebook needs the user to approve your 3rd party app to take actions so it needs the user to prove his/her identity to give this okay (otherwise you could just impersonate the user). Facebook needs to be the one asking for this okay too, not your app (hence the redirect to Facebook's site) because it would not be very secure at all if your app could just speak for the user. It is a pain though I will agree and Facebook's documentation does not help this in the slightest.