views:

84

answers:

1

I am migrating my old FB app to the new graph API using the PHP API

I have two pages: public ones (which require no user login) and private ones (which do)

So the code of every single php page in my application works as follows:

if (this_page_requires_user_login){
      $facebook = new Facebook(...) ;
      $session = $facebook->getSession ;
      if (!$session){
              $url =$facebook.getLoginUrl(array(next => current_page );
              echo "<fb:redirect url=$url/>" ;

}
// the rest of the code continues here

Now as you can see, this way of working forwards every single page to the login url and while it works, it is also slow and appends the &session={bla} string to very single url.

I need a way to check where a user is already logged in before I redirect him to loginpage. But i can not find such method in the php api. What's the best way to do this?

EDIT

This seemed to do the trick

if ($session) {
  try {
    $me = $facebook->api('/me');
    if ($me) {
       // here comes your code for user who is logged in
    }
  } catch (FacebookApiException $e) {
    login()
  }
}else{
 login()
}

function login(){

  $url =$facebook.getLoginUrl(array(next => current_page );


      echo "<fb:redirect url=$url/>" ;
}
+1  A: 

If I am reading your code correctly, only if no session is returned do you do the redirect? According to comments in Facebook's example: http://github.com/facebook/php-sdk/blob/master/examples/example.php (great place to this info huh?), even if you get a session back, you can't assume it's still valid. Only trying an API call that requires a logged in user will you know for sure. This is the best way I've seen to reliably determine login/logout status.

if ($session) {
  try {
    $me = $facebook->api('/me');
    if ($me) {
      //User should be logged in
    }
  } catch (FacebookApiException $e) {
    //User is not logged in
  }
}
jcmoney